編輯:關於 Android 程式設計
前兩篇把聯絡人讀了出來、排好序、也加上了字母索引。剩下最後一塊拼圖:頭像。這一步看似只是「多載一張圖」,實際上卻牽涉到 Bitmap 記憶體管理、清單滑動效能、以及生命週期收尾,是整個系列裡工程含量最高的部分。
聯絡人的頭像並不直接存在 Contacts 表中,而是透過 photo_id 關聯到 ContactsContract.Data 裡的一筆記錄,圖片以 BLOB 形式保存。因此取頭像的流程是:拿 photoId 組出 URI、查那筆 Data、取出 BLOB、再解碼成 Bitmap。
public static Bitmap getContactPhoto(Context context, long photoId,
BitmapFactory.Options options) {
if (photoId < 0) {
return null;
}
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photoId),
new String[] { Photo.PHOTO },
null, null, null);
if (cursor != null && cursor.moveToFirst() && !cursor.isNull(0)) {
byte[] photoData = cursor.getBlob(0);
if (options == null) {
options = new BitmapFactory.Options();
}
options.inTempStorage = new byte[16 * 1024];
options.inSampleSize = 2; // 降採樣,避免大圖直接爆記憶體
return BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options);
}
} catch (java.lang.Throwable error) {
// 解碼失敗不該讓整個清單崩掉,靜默降級為預設頭像
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
三個細節值得說明:inSampleSize = 2 把解碼尺寸縮為一半,頭像顯示在清單裡通常只有幾十 dp,全尺寸解碼是純浪費;catch (Throwable) 看似粗暴,但圖片解碼確實可能拋出 OutOfMemoryError 這類非 Exception 的錯誤,攔下來退回預設頭像比讓 App 崩潰合理;finally 中的 cursor.close() 則是鐵律——ContentProvider 的游標不關就是洩漏。
protected void setContactPhoto(Cursor cursor, final ImageView viewToUse, int column) {
long photoId = 0;
if (!cursor.isNull(column)) {
photoId = cursor.getLong(column);
}
final int position = cursor.getPosition();
viewToUse.setTag(new PhotoInfo(position, photoId));
if (photoId == 0) {
// 沒有頭像,直接顯示預設圖
viewToUse.setImageResource(R.drawable.avatar);
} else {
Bitmap photo = null;
SoftReference<Bitmap> ref = mBitmapCache.get(photoId);
if (ref != null) {
photo = ref.get();
if (photo == null) {
mBitmapCache.remove(photoId); // 已被 GC 回收,清掉殘留 entry
}
}
if (photo != null) {
// 命中快取,直接貼上
viewToUse.setImageBitmap(photo);
} else {
// 未命中:先顯示預設圖佔位,再排入背景載入佇列
viewToUse.setImageResource(R.drawable.avatar);
mItemsMissingImages.add(viewToUse);
if (mScrollState != OnScrollListener.SCROLL_STATE_FLING) {
sendFetchImageMessage(viewToUse);
}
}
}
}
這裡有兩個關鍵設計:
SoftReference 包裝 Bitmap,讓記憶體吃緊時 GC 能優先回收這些頭像,不至於拖累整個 App。mScrollState == SCROLL_STATE_FLING 時只把 ImageView 記進 mItemsMissingImages 待處理清單,不立刻觸發載入。使用者快速滑動時,網路與解碼的頻繁切換會讓畫面更卡;等滑動停下再批次載入,體感反而更順。private class ImageLoaderHandler extends Handler {
@Override
public void handleMessage(Message message) {
if (isFinishing()) {
return;
}
switch (message.what) {
case FETCH_IMAGE_MSG: {
final ImageView imageView = (ImageView) message.obj;
if (imageView == null) break;
final PhotoInfo info = (PhotoInfo) imageView.getTag();
if (info == null) break;
final long photoId = info.photoId;
if (photoId == 0) break;
SoftReference<Bitmap> photoRef = mBitmapCache.get(photoId);
if (photoRef == null) break;
Bitmap photo = photoRef.get();
if (photo == null) {
mBitmapCache.remove(photoId);
break;
}
synchronized (imageView) {
// 二次確認:這個 ImageView 可能已經被回收並改綁其他聯絡人
final PhotoInfo updatedInfo = (PhotoInfo) imageView.getTag();
long currentPhotoId = updatedInfo.photoId;
if (currentPhotoId == photoId) {
imageView.setImageBitmap(photo);
mItemsMissingImages.remove(imageView);
}
}
break;
}
}
}
public void clearImageFecthing() {
removeMessages(FETCH_IMAGE_MSG);
}
}
updatedInfo.photoId == photoId 這道二次檢查是整段程式最重要的一行。ListView 的 View 是重複利用的:當背景線程還在載入 A 的頭像時,使用者可能已經滑到別處,那個 ImageView 被回收去顯示 B 了。少了這道比對,就會出現「頭像錯位」這個經典 bug。
private class ImageLoader implements Runnable {
long mPhotoId;
private ImageView mImageView;
public ImageLoader(long photoId, ImageView imageView) {
this.mPhotoId = photoId;
this.mImageView = imageView;
}
public void run() {
if (isFinishing()) return;
if (Thread.interrupted()) return;
if (mPhotoId < 0) return;
Bitmap photo = ContactsUtils.getContactPhoto(getBaseContext(), mPhotoId, null);
if (photo == null) return;
mBitmapCache.put(mPhotoId, new SoftReference<Bitmap>(photo));
if (Thread.interrupted()) return;
Message msg = new Message();
msg.what = FETCH_IMAGE_MSG;
msg.obj = mImageView;
mHandler.sendMessage(msg);
}
}
private void processMissingImageItems(AbsListView view) {
for (ImageView iv : mItemsMissingImages) {
sendFetchImageMessage(iv);
}
}
protected void sendFetchImageMessage(ImageView view) {
final PhotoInfo info = (PhotoInfo) view.getTag();
if (info == null) return;
final long photoId = info.photoId;
if (photoId == 0) return;
mImageFetcher = new ImageLoader(photoId, view);
synchronized (ContactsList.this) {
if (sImageFetchThreadPool == null) {
sImageFetchThreadPool = Executors.newFixedThreadPool(3);
}
sImageFetchThreadPool.execute(mImageFetcher);
}
}
public void clearImageFetching() {
synchronized (ContactsList.this) {
if (sImageFetchThreadPool != null) {
sImageFetchThreadPool.shutdownNow();
sImageFetchThreadPool = null;
}
}
mHandler.clearImageFecthing();
}
固定 3 條線程是一個務實的取捨:太少則載入太慢,太多則 ContentProvider 查詢互相搶奪、反而更慢。注意這裡用 shutdownNow() 而非 shutdown(),是因為離開畫面時我們希望盡快中斷在途任務。
讓 Adapter 繼承 OnScrollListener,就能掌握滑動狀態:
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getCurrentFocus();
if (currentFocus != null) {
currentFocus.clearFocus();
}
}
mScrollState = scrollState;
if (scrollState == OnScrollListener.SCROLL_STATE_FLING) {
clearImageFetching(); // 快速滑動中,全部取消
} else {
processMissingImageItems(view); // 停下來了,批次載入
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// 目前用不到,保留空白實作
}
這一節最容易被跳過,卻是記憶體問題的主要來源:
@Override
protected void onDestroy() {
super.onDestroy();
// 1. 取消仍在飛行中的查詢
if (mQueryHandler != null) {
mQueryHandler.cancelOperation(QUERY_TOKEN);
mQueryHandler = null;
}
// 2. 清空待載入佇列與未處理的訊息
if (mAdapter != null && mAdapter.mItemsMissingImages != null) {
mAdapter.mItemsMissingImages.clear();
mAdapter.clearMessages();
}
// Workaround for Android Issue 8488
// https://code.google.com/p/android/issues/detail?id=8488
// 3. 回收 Bitmap 並清空快取
if (mAdapter != null && mAdapter.mBitmapCache != null) {
for (SoftReference<Bitmap> bitmap : mAdapter.mBitmapCache.values()) {
if (bitmap != null && bitmap.get() != null) {
bitmap.get().recycle();
bitmap = null;
}
}
mAdapter.mBitmapCache.clear();
}
}
三段收尾各有其道理:cancelOperation() 阻止查詢結果在 Activity 已死後回呼;清空 mItemsMissingImages 與待處理訊息,避免 Handler 持有已銷毀的 Activity;最後手動 recycle() Bitmap,則是針對舊版 Android 的 Bitmap 記憶體不計入 Java 堆、GC 無法妥善掌握其生命週期這一歷史問題所做的補償。
三篇看下來,一個「讀聯絡人並按字母展示」的功能,實際涉及的知識點是:ContentProvider 查詢與執行期權限、SQL 排序子句的巧用、AsyncQueryHandler 背景查詢、ViewHolder 與 ListView 重複利用、SectionIndexer 索引機制、Bitmap 解碼降採樣、記憶體快取策略、滑動狀態感知、以及生命週期資源釋放。這正是 Android 清單類介面的縮影——功能本身從不複雜,難的是把每一個邊界條件都照顧到。
完整程式碼可參考:https://download.csdn.net/detail/baidu_nod/7774203
最後提醒:這套寫法(SoftReference 快取、手動 recycle())屬於 Android 4.x 時代的最佳實務。在新專案中,RecyclerView 搭配 Glide、Coil 或 Picasso 這類圖片載入庫,會自動處理快取、生命週期綁定與記憶體回收,程式碼量能少掉一大半,也不容易出錯。理解本文的原理仍有價值——它解釋了那些函式庫底下究竟在做什麼。
Android 自定義 View 實作:彩色圓環統計圖
先看成果: 步驟一:釐清需要哪些變數 //-------------必須由外部提供的資料------------- private String[] str = n
Android Lint 使用指南:用靜態檢查做資源清理
做資源清理時,Android Lint 幾乎是必備工具。本文記錄 Lint 的用法,以及實戰中踩到的幾個坑。 Lint 是 SDK Tools 16(ADT 16)之後才
Android 學習筆記:SwipeRefreshLayout、RecyclerView 與 CardView 完全指南
前面我們介紹了 AlertDialog 以及幾個常用的 Dialog,包括 ProgressDialog 進度提示框、DatePickerDialog 日期選擇框和 Ti
UI Automator 入門實戰:從環境建置到第一支登入測試腳本
為什麼要學 UI Automator UI Automator 是 Android 官方的 UI 自動化測試框架,能模擬點擊、滑動、文字輸入等操作,把一組需要反覆執行的手