做 ListView 時要從網路載圖,最直覺的寫法是每個 ImageView 配一個 AsyncTask:
public class AsyncImageTask extends AsyncTask<String, Void, InputStream> {
private ImageView imageView;
public AsyncImageTask(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected InputStream doInBackground(String... params) {
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
inputStream = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream result) {
if (imageView != null && result != null) {
Bitmap bmp = BitmapFactory.decodeStream(result);
imageView.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
}
它能跑,需求也達到了,但問題不少:沒有快取,同一張圖會被反覆下載;每格一個任務,捲動時大量建立與銷毀;最致命的是它把 ImageView 直接抓在手上,而 ListView 的 convertView 會被回收再利用,於是圖片很容易「跑錯格」。後來主管把它換成了 AsyncImageLoader,差別立刻顯現。
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public static Drawable loadImageFromUrl(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Drawable.createFromStream(i, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
呼叫端傳入圖片網址與一個實作 ImageCallback 的物件。若快取裡已有這張圖,立刻回傳;若沒有,就開一條執行緒去下載,同時先回傳 null 讓版面墊上佔位圖;下載完成後透過 Handler 切回主執行緒,呼叫 imageLoaded() 把圖交出去。切執行緒這一步是關鍵——UI 只能由主執行緒更新。
下載完成後的行為被抽成 ImageCallback 介面,載入器本身不必知道呼叫端要怎麼呈現。系統因此變得靈活,要換成淡入動畫、要換成圓角處理,都只要換一個實作。
Java 的引用分四等:強引用、弱引用、軟引用、虛引用。強引用即使記憶體吃緊、丟出 OOM 也不會被回收;弱引用最容易被回收,適合數量不多但體積稍大的物件;軟引用則是折衷——記憶體充足時快取留得住,一旦即將 OOM,虛擬機在崩潰前會強制回收它,因此特別適合快取 App Icon 這類可重建的圖示;虛引用幾乎不具實用意義,主要用來觀察 GC 狀態,且必須搭配 ReferenceQueue。
用 HashMap 裝一組 SoftReference 暫存資料,就是這個模式最常見的落地方式。而對於那些需要反覆取得、又不常變動的內容,更該考慮落到本機檔案系統或資料庫做持久快取——事實上多數應用都是這麼做的。
class BookAdapter extends ArrayAdapter<BookInfo> {
AsyncImageLoader asyncImageLoader;
Context mContext;
BookAdapter(Context context, List<BookInfo> data) {
super(context, 0, data);
asyncImageLoader = new AsyncImageLoader();
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewCache holder;
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(com.slider.cn.R.layout.list_item, null);
holder = new ViewCache();
holder.icon = (ImageView) convertView.findViewById(com.slider.cn.R.id.note_icon);
holder.name = (TextView) convertView.findViewById(com.slider.cn.R.id.note_name);
holder.date = (TextView) convertView.findViewById(com.slider.cn.R.id.note_date);
convertView.setTag(holder);
} else {
holder = (ViewCache) convertView.getTag();
}
final BookInfo bookInfo = getItem(position);
holder.name.setText(bookInfo.getName().toString());
holder.date.setText(bookInfo.getInfo());
holder.icon.setTag(bookInfo.getUri());
Drawable drawable = asyncImageLoader.loadDrawable(bookInfo.getUri(), new ImageCallback() {
@Override
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
ImageView imageViewByTag = (ImageView) BookListView.this
.findViewWithTag(bookInfo.getUri());
if (imageViewByTag != null) {
imageViewByTag.setImageDrawable(imageDrawable);
}
}
});
if (drawable == null) {
holder.icon.setImageDrawable(drawable_waiting);
} else {
holder.icon.setImageDrawable(drawable);
}
return convertView;
}
static class ViewCache {
ImageView icon;
TextView name;
TextView date;
}
}
這裡有兩個細節值得留意:一是 convertView.setTag(holder) 搭配自寫的 ViewCache,避免了每格重複 findViewById;二是回呼中並非直接操作 ImageView,而是用 findViewWithTag 重新定位——這正是為了對抗 View 回收再利用,下載回來時那格可能早已被配給別筆資料,比對 tag 不符就果斷放棄。
最明顯的缺陷是沒有任何併發控制:快速捲動時可能同時產生二三十條下載執行緒,甚至更多。改法是換成固定大小的執行緒池。其次,同一張圖被重複送進下載佇列時沒有去重;再者,執行緒優先級完全沒有安排——通常你會希望剛進畫面的那批優先度最高,因為使用者只關心眼前這頁,已經捲過去的內容晚點補上無妨。這些都還能再打磨,但把上面這套跑通,已經足以應付大多數應用了。