Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

把 Handler 異步消息機制用進圖片加載:打造高效能的通用 ImageLoader

編輯:關於 Android 程式設計

上一篇介紹了 Android 異步消息處理機制,釐清了 Looper、Handler、Message 三者之間的關係。那篇最後提到一個想法:異步消息機制不該只用來在 MainActivity 裡更新 UI,它應該能用在哪裡?前陣子終於想到一個很實際的落點——大量圖片的加載工具類。

一、整體思路

一般的大量圖片加載(例如用 GridView 做相簿),會用到 LruCache、執行緒池、任務佇列這三個經典組合。那 Handler 在這套架構裡扮演什麼角色?有兩個位置:

第一,在 UI 執行緒上建立一個 Handler,當背景執行緒完成 Bitmap 解碼後,透過它回到主執行緒更新 ImageView。

第二,在初始化時另外開一條子執行緒,在裡面跑 Looper.prepare() 與 Looper.loop()。這條執行緒因此擁有自己的 MessageQueue,會一直掛在那裡等待消息;一旦消息送達,就從任務佇列中取出一個任務丟進執行緒池處理。

串起來就是這樣一條流水線:需要載入圖片時,先把任務放進佇列,再用子執行緒的 Handler 送一個「有任務來了」的通知;loop 執行緒收到後取出一個任務去解碼圖片;解碼完成,用主執行緒的 Handler 送消息回去更新畫面。

二、圖庫功能的實作

這個範例會先掃描手機內所有含圖片的資料夾,挑出圖片數量最多的那一個,再用 GridView 顯示其中的圖片。

1. 布局檔

<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>

2. MainActivity:掃描圖片

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);
    }
};

/**
 * 利用 ContentProvider 掃描手機中的圖片,找到 jpg 最多的資料夾
 */
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 mContentResolver = MainActivity.this.getContentResolver();
            // 只查詢 jpeg 和 png
            Cursor mCursor = mContentResolver.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 (mCursor.moveToNext()) {
                String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                File parentFile = new File(path).getParentFile();
                String dirPath = parentFile.getAbsolutePath();

                // 用 HashSet 防止重複掃描同一個資料夾
                if (mDirPaths.contains(dirPath)) {
                    continue;
                } else {
                    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;
                }
            }
            mCursor.close();
            mDirPaths = null;   // 掃描完成,輔助用的 HashSet 可以釋放
            mHandler.sendEmptyMessage(0x110);
        }
    }).start();
}

這裡有兩個值得留意的小細節:

用 HashSet 去重。如果不做这个判斷,手機裡有個裝了三千多張圖的資料夾,就會被反覆掃描三千多次,處理器時間與記憶體的消耗相當可觀。

路徑與檔名分開存。圖片路徑通常比檔名長得多。假設有 3000 張圖,路徑長度 30、檔名平均 10:把完整路徑存進 List 需要 (30+10)×3000 = 120000 個字元;而只存檔名、路徑當作獨立變數傳入,只需 30+10×3000 = 30030。圖片越多,省下的記憶體越明顯。

3. GridView 的 Adapter

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, final ViewGroup parent) {
        ViewHolder holder = null;
        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 幾乎沒兩樣,甚至在 getView 裡都看不到常見的 tag 比對防錯位邏輯——那些細節全被 ImageLoader 吃掉了。使用端只需要一行:

mImageLoader.loadImage(mDirPath + "/" + mData.get(position), holder.mImageView);

4. ImageLoader:核心的到來

先是懶漢式單例,預設開一條執行緒、採用 LIFO 策略:

public static ImageLoader getInstance() {
    if (mInstance == null) {
        synchronized (ImageLoader.class) {
            if (mInstance == null) {
                mInstance = new ImageLoader(1, Type.LIFO);
            }
        }
    }
    return mInstance;
}

建構子把工作交給 init:

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();   // 取得號誌,確保 Handler 初始化完成前不會被使用
            } 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() 之後,它就擁有自己的消息佇列並進入無限等待;mPoolThreadHander 送出的消息會直接進到這個佇列,收到後便取出一個任務丟給執行緒池。

第二,mSemaphore(號誌數為 1)的作用是解決初始化競態。Handler 是在子執行緒建立的,而主執行緒可能立刻就要用它;雖然初始化很快,但無法百分之百保證已經完成。因此在子執行緒初始化前先 acquire()、完成後 release(),主執行緒這邊則這樣防呆:

private synchronized void addTask(Runnable runnable) {
    try {
        // 若 Handler 尚未初始化完成,就在這裡等待
        if (mPoolThreadHander == null) mSemaphore.acquire();
    } catch (InterruptedException e) { }
    mTasks.add(runnable);
    mPoolThreadHander.sendEmptyMessage(0x110);
}

想驗證的話,把 mSemaphore 相關程式碼註解掉,再在初始化 mPoolThreadHander 之後加上 Thread.sleep(1000),空指針異常立刻就會出現。

初始化完成後,getView 裡呼叫的就是 loadImage:

public void loadImage(final String path, final ImageView imageView) {
    imageView.setTag(path);   // 打上標記,用於後續比對

    // 以下在 UI 執行緒執行
    if (mHandler == null) {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
                ImageView imageView = holder.imageView;
                Bitmap bm = holder.bitmap;
                String path = holder.path;
                // 比對 tag,避免清單滾動時圖片錯位
                if (imageView.getTag().toString().equals(path)) {
                    imageView.setImageBitmap(bm);
                }
            }
        };
    }

    Bitmap bm = getBitmapFromLruCache(path);
    if (bm != null) {
        // 命中快取,直接更新
        ImgBeanHolder holder = new ImgBeanHolder();
        holder.bitmap = bm;
        holder.imageView = imageView;
        holder.path = path;
        Message message = Message.obtain();
        message.obj = holder;
        mHandler.sendMessage(message);
    } else {
        addTask(new Runnable() {
            @Override
            public void run() {
                ImageSize imageSize = getImageViewWidth(imageView);
                int reqWidth = imageSize.width;
                int reqHeight = imageSize.height;

                Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth, reqHeight);
                addBitmapToLruCache(path, bm);

                ImgBeanHolder holder = new ImgBeanHolder();
                holder.bitmap = getBitmapFromLruCache(path);
                holder.imageView = imageView;
                holder.path = path;

                Message message = Message.obtain();
                message.obj = holder;
                mHandler.sendMessage(message);
                mPoolSemaphore.release();
            }
        });
    }
}

幾個關鍵點:開頭先把 path 設為 ImageView 的 tag,handleMessage 裡再拿它跟目前 tag 比對,不一致就跳過設定——這是防止快速滾動時圖片錯位最簡單有效的手法。命中 LruCache 就直接發消息更新;未命中則包裝成 Runnable 丟進任務佇列。

解碼前先量測 ImageView 的實際尺寸,用於等比縮放:

private ImageSize getImageViewWidth(ImageView imageView) {
    ImageSize imageSize = new ImageSize();
    final DisplayMetrics displayMetrics = 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 = displayMetrics.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 = displayMetrics.heightPixels;

    imageSize.width = width;
    imageSize.height = height;
    return imageSize;
}

接著用兩次解碼的技巧做取樣壓縮——第一次只讀取邊界資訊,第二次才真正解碼:

private Bitmap decodeSampledBitmapFromResource(String pathName, int reqWidth, int reqHeight) {
    // 第一次解析:只要尺寸,不配置像素記憶體
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, options);

    // 計算 inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // 第二次解析:真正解碼
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(pathName, options);
}

這是全篇最關鍵的一段。原始圖片動輒數 MB,若不做取樣直接塞進 ImageView,很快就會 OutOfMemoryError。inJustDecodeBounds = true 讓第一次解碼只回傳寬高而不配置像素記憶體,算出合適的 inSampleSize 後再解一次,記憶體用量立刻降到合理範圍。

最後回來看 addTask 與 mPoolSemaphore 這號誌的必要性:

addTask 之後,loop 執行緒會立刻去佇列取任務丟給執行緒池。但執行緒池內部本身也維護著一個佇列,「取出任務」這個動作瞬間就完成了,於是外層任務佇列永遠維持空狀態。結果就是:使用者明明設定了 LIFO,卻感覺完全沒有效果。因此按照執行緒池的工作執行緒數量配置一個號誌,確保任務真正執行完畢後才去取下一個,LIFO 才能發揮作用。有興趣可以把所有 mPoolSemaphore 相關程式碼註解掉實測看看。

三、為什麼用異步消息機制,而不是裸的執行緒

貼一下實測效果。我手機裡最大的資料夾約 3000 張圖,載入相當順暢:

真機錄影難免掉幀,但注意看:中間我瘋狂拖動捲軸,圖片幾乎都是瞬間顯示。

補充一點實務經驗:FIFO 模式下如果不在控件层做處理,使用者慢慢滑時效果很好,但手機裡有幾千張圖並一口氣滑到底時,最後一屏可能要等上幾秒。可以考慮在拖動過程中暫停載入、停下來才載入;或者偵測到快速 fling 時先不載入,等速度降下來再說。LIFO 模式在這方面的體驗明顯更好——不管理拉多快,最終停下來的那一屏都會立即顯示。

最後談談為何要用異步消息機制當作背景執行緒的骨架。直接用一條裸執行緒當然也行,但那樣就得在 run() 裡寫 while(true),每隔兩百毫秒甚至更短時間去輪詢任務佇列,沒任務就 sleep。問題是長時間沒有新任務時,這條執行緒仍在持續喚醒、持續消耗 CPU。

異步消息機制則不一樣:只有送消息時才會被喚醒,沒有任務時就安靜地阻塞在 Looper.loop() 上,完全不佔用運算資源。更別提這套機制是 Android 平台內建、經過大量驗證的實作,無論穩定性還是效率,都遠比我們自己湊一個輪詢執行緒來得可靠。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved