編輯:關於 Android 程式設計
大量圖片載入(例如用 GridView 做手機相冊)通常會用到 LruCache、線程池與任務隊列。異步消息機制在這裡扮演兩個角色:
1. 主線程的 Handler:Bitmap 載入完成後,回到 UI 線程更新 ImageView。
2. 子線程的 Handler:在圖片載入類初始化時建立一個迴圈線程,該線程內有 Looper 與 MessageQueue,持續等待消息;有任務時依排程策略(FIFO/LIFO)從隊列取出一個丟進線程池執行。
簡化流程:需要載入圖片 → 任務進隊列 → 子線程 Handler 發消息通知 → Looper 取出任務交給線程池 → 完成後由主線程 Handler 發消息更新 UI。
程式先掃描手機內所有含圖片的資料夾,挑出圖片最多的那一個,用 GridView 呈現。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/id_gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@android:color/transparent"
android:columnWidth="90dip"
android:gravity="center"
android:horizontalSpacing="20dip"
android:listSelector="@android:color/transparent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="20dip" />
</RelativeLayout>
public class MainActivity extends Activity {
private ProgressDialog mProgressDialog;
private int mPicsSize;
private File mImgDir;
private List<String> mImgs;
private GridView mGirdView;
private ListAdapter mAdapter;
/** 避免同一資料夾被重複掃描 */
private HashSet<String> mDirPaths = new HashSet<String>();
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
mProgressDialog.dismiss();
mImgs = Arrays.asList(mImgDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.endsWith(".jpg");
}
}));
// 只存圖片名稱,路徑另外傳入,大幅降低記憶體
mAdapter = new MyAdapter(getApplicationContext(), mImgs,
mImgDir.getAbsolutePath());
mGirdView.setAdapter(mAdapter);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGirdView = (GridView) findViewById(R.id.id_gridView);
getImages();
}
/** 利用 ContentProvider 找出圖片最多的資料夾,運行於子線程 */
private void getImages() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "暫無外部存儲", Toast.LENGTH_SHORT).show();
return;
}
mProgressDialog = ProgressDialog.show(this, null, "正在加載...");
new Thread(new Runnable() {
@Override
public void run() {
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = MainActivity.this.getContentResolver();
Cursor cursor = cr.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[]{"image/jpeg", "image/png"},
MediaStore.Images.Media.DATE_MODIFIED);
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndex(
MediaStore.Images.Media.DATA));
File parentFile = new File(path).getParentFile();
String dirPath = parentFile.getAbsolutePath();
if (mDirPaths.contains(dirPath)) {
continue;
}
mDirPaths.add(dirPath);
int picSize = parentFile.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.endsWith(".jpg");
}
}).length;
if (picSize > mPicsSize) {
mPicsSize = picSize;
mImgDir = parentFile;
}
}
cursor.close();
mDirPaths = null; // 釋放輔助集合
mHandler.sendEmptyMessage(0x110);
}
}).start();
}
}
兩個細節值得注意:
其一,用一個臨時的 HashSet 記錄已掃描過的資料夾。若某資料夾有三千張圖片,不做判斷就會被掃描三千次,CPU 與記憶體的浪費相當可觀。
其二,Adapter 只保存圖片檔名,資料夾路徑作為獨立變數傳入。假設有 3000 張圖,路徑長度 30、檔名平均長度 10,全存路徑需要 (30+10)×3000 = 120000 字元;分開存則只需 30 + 10×3000 = 30030。圖片越多,差距越明顯。
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
private String mDirPath;
private LayoutInflater mInflater;
private ImageLoader mImageLoader;
public MyAdapter(Context context, List<String> mData, String dirPath) {
this.mContext = context;
this.mData = mData;
this.mDirPath = dirPath;
mInflater = LayoutInflater.from(mContext);
mImageLoader = ImageLoader.getInstance();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.grid_item, parent, false);
holder.mImageView = (ImageView) convertView
.findViewById(R.id.id_item_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mImageView.setImageResource(R.drawable.friends_sends_pictures_no);
mImageLoader.loadImage(mDirPath + "/" + mData.get(position),
holder.mImageView);
return convertView;
}
private final class ViewHolder {
ImageView mImageView;
}
}
與傳統 Adapter 幾乎沒差別,全部都濃縮成一行:
mImageLoader.loadImage(mDirPath + "/" + mData.get(position), holder.mImageView);
public static ImageLoader getInstance() {
if (mInstance == null) {
synchronized (ImageLoader.class) {
if (mInstance == null) {
mInstance = new ImageLoader(1, Type.LIFO);
}
}
}
return mInstance;
}
private ImageLoader(int threadCount, Type type) {
init(threadCount, type);
}
private void init(int threadCount, Type type) {
// 後台 loop 線程
mPoolThread = new Thread() {
@Override
public void run() {
try {
mSemaphore.acquire(); // 等到初始化就緒
} catch (InterruptedException e) { }
Looper.prepare();
mPoolThreadHander = new Handler() {
@Override
public void handleMessage(Message msg) {
mThreadPool.execute(getTask());
try {
mPoolSemaphore.acquire();
} catch (InterruptedException e) { }
}
};
mSemaphore.release();
Looper.loop();
}
};
mPoolThread.start();
// 使用最大可用記憶體的 1/8 作為快取
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mLruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
mThreadPool = Executors.newFixedThreadPool(threadCount);
mPoolSemaphore = new Semaphore(threadCount);
mTasks = new LinkedList<Runnable>();
mType = type == null ? Type.LIFO : type;
}
這個子線程執行了 Looper.prepare()、Looper.loop(),因此它擁有自己的 MessageQueue,並進入無限等待。mPoolThreadHander 發出的消息都會進到這條線程的隊列,收到後取出一個任務丟進線程池。
關於 mSemaphore(計數為 1):Handler 在子線程建立,但主線程可能立刻要使用它。雖然初始化很快,仍無法保證時序,因此初始化前先 acquire(),完成後 release()。對外的 addTask() 相對應地檢查:
private synchronized void addTask(Runnable runnable) {
try {
// 若 Handler 尚未建立,acquire 會等到子線程初始化完成
if (mPoolThreadHander == null) {
mSemaphore.acquire();
}
} catch (InterruptedException e) { }
mTasks.add(runnable);
mPoolThreadHander.sendEmptyMessage(0x110);
}
想驗證這段邏輯,可以把 mSemaphore 相關程式碼註解掉,並在建立 Handler 前 Thread.sleep(1000),就會重現空指標錯誤。
public void loadImage(final String path, final ImageView imageView) {
imageView.setTag(path); // 標記,用於防止圖片錯位
if (mHandler == null) {
mHandler = new Handler() { // 此 Handler 建立於 UI 線程
@Override
public void handleMessage(Message msg) {
ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
ImageView iv = holder.imageView;
// 只有 tag 仍等於當初的 path 才設定,避免捲動時錯位
if (iv.getTag() != null && iv.getTag().equals(holder.path)) {
iv.setImageBitmap(holder.bitmap);
}
}
};
}
Bitmap bm = getBitmapFromLruCache(path);
if (bm != null) {
// 命中快取,直接回主線程設定
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = bm;
holder.imageView = imageView;
holder.path = path;
mHandler.sendMessage(Message.obtain().obj != null ? null : wrap(holder));
return;
}
addTask(new Runnable() {
@Override
public void run() {
ImageSize size = getImageViewWidth(imageView);
Bitmap bm = decodeSampledBitmapFromResource(path, size.width, size.height);
addBitmapToLruCache(path, bm);
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = getBitmapFromLruCache(path);
holder.imageView = imageView;
holder.path = path;
Message msg = mHandler.obtainMessage();
msg.obj = holder;
mHandler.sendMessage(msg);
mPoolSemaphore.release();
}
});
}
private Message wrap(ImgBeanHolder holder) {
Message msg = mHandler.obtainMessage();
msg.obj = holder;
return msg;
}
流程拆解:
先為 ImageView 設定 tag,並在 UI 線程建立用來更新畫面的 Handler。收到消息時比對 tag 與 path,相同才設定 Bitmap,這一步是防止快速捲動時圖片錯位的關鍵。
接著查 LruCache。命中就直接發消息回主線程;未命中則建立 Runnable 加入任務隊列,由後台線程取出丟進線程池。
背景任務中依 ImageView 的實際尺寸計算 inSampleSize 做降採樣解碼,再寫入快取,最後回主線程更新。
private ImageSize getImageViewWidth(ImageView imageView) {
ImageSize size = new ImageSize();
final DisplayMetrics dm = imageView.getContext()
.getResources().getDisplayMetrics();
final LayoutParams params = imageView.getLayoutParams();
int width = params.width == LayoutParams.WRAP_CONTENT
? 0 : imageView.getWidth();
if (width <= 0) width = params.width;
if (width <= 0) width = getImageViewFieldValue(imageView, "mMaxWidth");
if (width <= 0) width = dm.widthPixels;
int height = params.height == LayoutParams.WRAP_CONTENT
? 0 : imageView.getHeight();
if (height <= 0) height = params.height;
if (height <= 0) height = getImageViewFieldValue(imageView, "mMaxHeight");
if (height <= 0) height = dm.heightPixels;
size.width = width;
size.height = height;
return size;
}
private Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight) {
// 第一次只讀取邊界資訊
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 第二次才真正解碼
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
這個信號量常被誤解。addTask 之後,後台線程會立刻「從任務隊列取出一個任務」丟進線程池。但線程池內部自己也有一個隊列,這個動作幾乎瞬間完成,等於任務被快速搬進線程池的隊列,而自建的任務隊列永遠接近空。
結果就是:即使你設定了 LIFO,也感受不到效果——因為自建隊列裡隨時只有一個元素。加上計數等於線程數的信號量後,必須等線程池中的任務執行完、呼叫 release(),才會再取下一個任務,LIFO 的行為才真正顯現。把 mPoolSemaphore 相關程式碼全部註解掉實測一次,就能看出差別。
單純開一條子線程也能做,但那條線程得在 run 裡 while(true) 反覆輪詢任務隊列,沒任務時 Thread.sleep(200)。問題是即使長時間沒有新任務,它仍會持續喚醒、持續查詢,白白消耗電力。
異步消息機制則是「有消息才執行」,閒置時線程阻塞在 Looper.loop() 完全不佔用 CPU;而且這是 Android 系統內建的機制,穩定性與效率都優於自行實作的輪詢。
效果實測:測試機中最大的資料夾約三千張圖片,快速拖動捲軸時圖片幾乎是瞬間顯示。

最後比較兩種排程策略:FIFO 在「慢慢滑」時體驗不錯,但使用者若從頭飛速滑到尾,最後一屏的圖片會排在隊列最後,可能要等一會兒;LIFO 則不論滑多快,停下來的那一屏永遠優先處理,體驗明顯更好。折衷做法是監聽 FLING 狀態,快速滑動期間暫停載入,或使用 VelocityTracker 判斷速度下降後再啟動載入。
補充一點:範例基於早期 API 撰寫,ProgressDialog 已不建議使用(改用 ProgressIndicator 或自訂 View),getImageViewFieldValue 用了反射存取 mMaxWidth 私有欄位,在新版本 Android 上欄位名稱可能改變而失效。若要在新專案使用,建議改用 Glide 或 Coil 這類成熟框架,它們在快取策略、生命週期綁定與請求取消上都做得更完整。
小米推送接入實記:從後台建項到代碼落地的完整流程
公司項目需要接入推送,技術選型後我們用了小米推送。從註冊帳號到消息真正落到通知欄,中間踩了不少流程上的坑,這裡把完整步驟記錄下來。 一、後台配置 1、註冊並登入小米開放
瀏覽器與微信中喚起本地 APP 的實踐思路
問題場景 在行動裝置中,連結是重要的傳播媒介。很多時候,我們希望使用者從瀏覽器或微信回到 APP,甚至直接進入指定頁面。但這個過程會遇到未安裝引導、平台限制、Univer
Android 仿淘寶商品圖片瀏覽:雙 ScrollView 滑動容器實作
商品詳情頁的滑動節奏在電商 App 中,商品圖片常放在上方,當使用者滑到圖片區底部,會看到提示,再繼續拖曳才會進入商品描述。這種效果看似簡單,但要做到不卡頓、不跳動,需要
從 setContentView 源碼看 Android 是怎麼把你的 XML 掛上螢幕的
先提一句:當初你選擇繞開的問題,總會在未来的某一天原封不動地回到你面前。所以第一次遇到它的時候,別逃。 很多剛入門的朋友都很好奇一件事——寫在 XML 裡的布局,究竟是經