編輯:Android 程式設計入門
在 Android 應用中,加載並展示網絡圖片是非常常見的需求。本文將從零開始,帶你實現一個網絡圖片查看器,並逐步引入線程通信、本地緩存等實用知識。
確定圖片的網址
發送 HTTP 請求
URL url = new URL(address); //獲取連接對象,此時並未真正建立連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //設置連接和讀取超時 conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //設置請求方法,注意必須大寫 conn.setRequestMethod("GET"); //getResponseCode() 會建立連接並返回響應碼,200 表示成功 conn.getResponseCode();服務器的圖片以流的形式返回,需要讀取並解析為圖片
//拿到服務器返回的輸入流 InputStream is = conn.getInputStream(); //把流中的數據讀取出來,並構造為圖片 Bitmap bm = BitmapFactory.decodeStream(is);將圖片設置為 ImageView 的顯示內容
ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap(bm);添加網絡權限
<uses-permission android:name="android.permission.INTERNET"/>android.os.Handler handler = new android.os.Handler(){ //此方法運行在主線程中,可刷新 UI public void handleMessage(Message msg) { } };在子線程中通過 Handler 發送消息:
Message msg = new Message(); //obj 可攜帶任意對象 msg.obj = bm; //what 相當於標簽,用於區分不同消息 msg.what = 1; handler.sendMessage(msg);通過 switch 區分不同消息並分別處理:
public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: ImageView iv = (ImageView) findViewById(R.id.iv); Bitmap bm = (Bitmap) msg.obj; iv.setImageBitmap(bm); break; case 2: Toast.makeText(MainActivity.this, "請求失敗", 0).show(); break; } }總結:只要消息隊列中有消息,handleMessage() 便會被調用。子線程若需刷新 UI,只需通過 Handler 的 sendMessage() 向隊列發送一條消息,即可觸發 handleMessage()。
將服務器返回的流數據寫入本地文件:
//1.拿到服務器返回的輸入流 InputStream is = conn.getInputStream(); //2.把流中的數據寫入本地文件 FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b)) != -1){ fos.write(b, 0, len); }此後創建 Bitmap 的代碼改為從文件讀取:
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());每次發請求前先檢測緩存中是否存在同名圖片,若存在則直接讀取緩存,避免重複網絡請求。
<com.loopj.android.image.SmartImageView/>SmartImageView siv = (SmartImageView) findViewById(R.id.siv); siv.setImageUrl("https://192.168.1.102:8080/dd.jpg");發送 GET 請求並獲取響應
URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); if(conn.getResponseCode() == 200){ }讀取服務器返回的流,將 HTML 源碼轉為字符串
byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = is.read(b)) != -1){ bos.write(b, 0, len); } String text = new String(bos.toByteArray());亂碼是由於服務端與客戶端字符集不一致導致的,可手動指定碼表解決:
text = new String(bos.toByteArray(), "gb2312");GET 方式會將數據直接拼接在 URL 末尾:
final String path = "https://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;瀏覽器發送請求時會對數據進行 URL 編碼,我們在寫代碼時也需要為中文進行編碼:
String path = "https://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;POST 方式通過流將數據寫給服務器,協議頭中需增加兩個屬性:Content-Type(描述數據的 mimetype)與 Content-Length(描述數據長度)。
//添加 POST 多出來的兩個請求頭屬性 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + ""); //允許打開 POST 請求的輸出流 conn.setDoOutput(true); //獲取輸出流並寫入要提交的數據 OutputStream os = conn.getOutputStream(); os.write(data.getBytes());
Android 主題切換實作:SkinUtils 與沉浸式狀態欄
主題切換思路先在 styles 或 themes 準備多套主題,再用工具類保存目前主題編號,最後在 BaseActivity 初始化。SkinUtils工具類可透過 Sh
Android 四大組件之 BroadcastReceiver 廣播接收器詳解
BroadcastReceiver 是 Android 四大組件之一,本文從基本概念、使用方法、生命週期到廣播種類,系統性地梳理這一機制。 一、基本概念 1、Broadc
Android 熱修復實踐:AndFix 開源框架接入指南
一直關注 App 熱修復技術的發展。在熱修復框架流行之前,應用上線後一旦發現小 Bug,就得馬上發新版本。我曾親身經歷過一周發兩個版本,著實折騰用戶。正因如此,開始認真
Android 頭像設定教學:相簿選圖、拍照與裁剪
在許多社群與通訊應用中,頭像設定通常包含三個步驟:從本地相簿選擇圖片、使用相機拍照,以及裁剪成符合介面的方形或圓形頭像。完成後,再將結果顯示於畫面並儲存到本機。效果示意: