編輯:關於 Android 開發
下載網路圖片時,如果網路狀況不穩,很容易出現圖片出不來的情況。問題往往不在你的邏輯,而在於直覺寫法本身有缺陷。
// 取得 connection(細節省略) conn = getURLConnection(url); is = conn.getInputStream(); // 直接從串流解碼 Bitmap bitmap = BitmapFactory.decodeStream(is);
decodeStream() 會邊讀邊解,一旦連線在中途斷掉或速度過慢,讀到的位元組不足,解碼就直接失敗,回傳 null。使用者看到的就是一片空白。
int length = (int) conn.getContentLength();
if (length != -1) {
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}
這樣做的好處很明確:網路再慢,只要連線沒斷,迴圈就會持續把資料收滿,收完才交給解碼器。只要圖片真的存在,就下載得下來。
上面這段程式碼有個前提——得先知道長度。但 Content-Length 並非總是可靠(chunked 編碼時甚至回傳 -1)。若改用 java.nio.ByteBuffer,就不必事先知道大小,也省掉自己搬移陣列的動作:
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] temp = new byte[512];
int readLen;
while ((readLen = is.read(temp)) > 0) {
if (buffer.remaining() < readLen) {
ByteBuffer bigger = ByteBuffer.allocate(buffer.capacity() * 2);
bigger.put(buffer.array(), 0, buffer.position());
buffer = bigger;
}
buffer.put(temp, 0, readLen);
}
bitmap = BitmapFactory.decodeByteArray(buffer.array(), 0, buffer.position());
public synchronized Bitmap getBitMap(Context c, String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
return BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultimg);
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = (int) conn.getContentLength();
if (length != -1) {
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}
} catch (IOException e) {
return BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultimg);
}
return bitmap;
}
第一,這個方法用了 synchronized,代表所有呼叫被序列化,下載多張圖會互相排隊;實務上應把網路移到背景執行緒,並移除方法級別的鎖。
第二,網路請求一定要設連線與讀取逾時(setConnectTimeout/setReadTimeout),否則卡住的連線會佔著執行緒不放。
第三,認真做的話不必自己造輪子:Glide 或 Coil 已經處理好重試、逾時、磁碟快取、記憶體快取與生命週期綁定,還能自動避免列表捲動時的圖片錯位。上面這些原理值得懂,但產品程式碼請用成熟函式庫。
Android 自訂 View 屬性全流程:attrs 與 TypedArray 詳解
Android 自訂 View 屬性全流程:attrs 與 TypedArray 詳解 自從開始深入研究 Android 自訂控制項之後,最繞不過去的一關就是「屬性」:怎
谷歌電子市場(九):詳情界面實現
谷歌電子市場(九):詳情界面實現 1. 詳情頁(HomeDetailActivity) @Override protected void onCreate(Bundle
MySQL 新特性解析:mysql_config_editor 加密原理與原始碼
MySQL 新特性解析:mysql_config_editor 加密原理與原始碼 從 MySQL 5.6 開始,官方推出了加密工具 mysql_config_editor
用 Kotlin 打造 Android 自訂視圖(KAD 06):多構造函數的優雅寫法
作者:Antonio Leiva | 時間:2016 年 12 月 27 日 | 原文:antonioleiva.com/custom-views-android-kot