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

自製 ImageLoader:從 LruCache 到非同步圖片載入的完整實作

編輯:關於 Android 程式設計

先看幾張效果圖:



在載入大量圖片時,我們採用後進先出策略(滑到哪裡就先載入哪裡的圖片),既節省記憶體,使用者體驗也更好。下面就來打造自己的 ImageLoader。

① 定義基本成員

private static final int MSG_ADDTASK = 0x001;

private LruCache<String, Bitmap> mLruCache;   // 圖片緩存核心物件
private ExecutorService mThreadPool;          // 線程池
private LinkedList<Runnable> mTaskQueue;      // 任務佇列
private Thread mPollThread;                   // 後台輪詢線程
private Handler mUIThread;                    // UI 線程的 Handler,負責把圖片回顯到介面
private Handler mPollThreadHandler;           // 後台線程的 Handler,用來派發任務
private Semaphore mSemphorePollThreadHandler = new Semaphore(0); // 用於 addTask() 與 mPollThreadHandler 的同步
private Semaphore mSemphoreTreadPool;         // 控制線程池忙碌時不取新任務
private Type mType = Type.LIFO;               // 佇列調度模式,預設後進先出

/** 佇列調度方式:先進先出 / 後進先出 */
private enum Type {
    FIFO, LIFO
}

LruCache 是 Android 提供的緩存工具類,採「最近最少使用」演算法淘汰資料,非常適合做圖片緩存。

② 單例取得方式

private static ImageLoader mInstance;

private ImageLoader(int threadCount, Type type) {
    init(threadCount, type);
}

public static ImageLoader getInstance() {
    if (mInstance == null) {
        synchronized (ImageLoader.class) {
            if (mInstance == null) {
                // 線程池 3 個線程,圖片後進先載入
                mInstance = new ImageLoader(3, Type.LIFO);
            }
        }
    }
    return mInstance;
}

③ init():初始化成員與後台線程

private void init(int threadCount, Type type) {
    mType = type;
    mSemphoreTreadPool = new Semaphore(3);  // 設為 3,第四個線程進來時會被阻塞

    // 後台輪詢線程
    mPollThread = new Thread() {
        @Override
        public void run() {
            Looper.prepare();   // 準備 Looper
            mPollThreadHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case MSG_ADDTASK:
                            mThreadPool.execute(getTask());  // 從佇列取出一個任務丟進線程池
                            try {
                                // 此時已有三個線程在執行,第四個會被阻塞
                                mSemphoreTreadPool.acquire();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            // 釋放信號量,解除 addTask() 中 acquire 的阻塞
                            // 作用是防止 mPollThreadHandler 還沒建立完就發送訊息
                            mSemphorePollThreadHandler.release();
                            break;
                    }
                }
            };
            Looper.loop();  // 開始循環
        }
    };
    mPollThread.start();

    // 緩存容量取最大可用記憶體的 1/8
    int maxMemory = (int) Runtime.getRuntime().maxMemory();
    int cacheMemory = maxMemory / 8;
    mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getHeight() * bitmap.getRowBytes();  // 每張圖片佔用的位元組數
        }
    };

    mThreadPool = Executors.newFixedThreadPool(threadCount);
    mTaskQueue = new LinkedList<Runnable>();   // 用 LinkedList 方便取出任意位置的任務
}

/** 加入一個任務 */
private synchronized void addTask(Runnable task) {
    mTaskQueue.add(task);
    try {
        if (mPollThreadHandler == null) {
            // Handler 還沒建立好,先阻塞,直到 release 被呼叫
            mSemphorePollThreadHandler.acquire();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    mPollThreadHandler.sendEmptyMessage(MSG_ADDTASK);
}

/** 取出一個任務 */
private Runnable getTask() {
    if (mType == Type.FIFO) {
        return mTaskQueue.removeFirst();
    } else if (mType == Type.LIFO) {
        return mTaskQueue.removeLast();
    }
    return null;
}

④ 核心方法 loadImage()

依圖片路徑與 ImageView,把圖片設定到元件上:

public void loadImage(final ImageView imageView, final String path) {
    // 記下 path,防止圖片載入過程中因為 View 復用而錯亂
    imageView.setTag(path);

    mUIThread = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 取出圖片並設定到 ImageView
            ImageHolder imageHolder = (ImageHolder) msg.obj;
            ImageView imageView = imageHolder.imageView;
            Bitmap bitmap = imageHolder.bitmap;
            String path = imageHolder.path;
            if (imageView.getTag().toString().equals(path)) {
                imageView.setImageBitmap(bitmap);
            }
        }
    };

    // 先查緩存
    Bitmap bm = getBitmapFromLruCache(path);
    if (bm != null) {
        sendBitmapToUIHandler(imageView, bm, path);
    } else {
        addTask(new Runnable() {
            @Override
            public void run() {
                // 取得目標顯示尺寸
                ImageSize imageSize = getImageViewSize(imageView);
                // 依尺寸壓縮圖片
                Bitmap bitmap = decodeSempledBitmapFromPath(path, imageSize);
                // 放入 LruCache
                addBitmapToLruCache(bitmap, path);
                // 交給 UI 線程刷新
                sendBitmapToUIHandler(imageView, bitmap, path);
                // 釋放線程佔用的信號量
                mSemphoreTreadPool.release();
            }
        });
    }
}

/** 把圖片資訊送到主線程,更新介面 */
private void sendBitmapToUIHandler(ImageView imageView, Bitmap bitmap, String path) {
    ImageHolder imageHolder = new ImageHolder();
    imageHolder.imageView = imageView;
    imageHolder.bitmap = bitmap;
    imageHolder.path = path;

    Message msg = Message.obtain();
    msg.obj = imageHolder;
    mUIThread.sendMessage(msg);
}

/** Handler 傳輸用的資料載體 */
private class ImageHolder {
    ImageView imageView;
    Bitmap bitmap;
    String path;
}

/** ImageView 的尺寸 */
private class ImageSize {
    int width;
    int height;
}

⑤ 圖片處理相關方法

/** 取得圖片要顯示的大小 */
private ImageSize getImageViewSize(ImageView imageView) {
    DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics();
    ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();

    int width = imageView.getWidth();
    if (width < 0) {
        width = layoutParams.width;
    }
    if (width < 0) {
        width = getFieldValue(imageView, "mMaxWidth");
    }
    if (width < 0) {
        width = displayMetrics.widthPixels;
    }

    int height = imageView.getHeight();
    if (height < 0) {
        height = layoutParams.height;
    }
    if (height < 0) {
        height = getFieldValue(imageView, "mMaxHeight");
    }
    if (height < 0) {
        height = displayMetrics.heightPixels;
    }

    ImageSize imageSize = new ImageSize();
    imageSize.height = height;
    imageSize.width = width;
    return imageSize;
}

/** 反射取得欄位值 */
private int getFieldValue(Object obj, String fieldName) {
    int value = 0;
    try {
        Field field = ImageView.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        int fieldInt = field.getInt(obj);
        if (fieldInt > 0 && fieldInt < Integer.MAX_VALUE) {
            value = fieldInt;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return value;
}

/** 壓縮圖片 */
private Bitmap decodeSempledBitmapFromPath(String path, ImageSize imageSize) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;   // 只讀邊界,不把像素載入記憶體
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = caculateInSampleSize(options, imageSize);  // 設定取樣率
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}

/** 計算最佳取樣率 */
private int caculateInSampleSize(BitmapFactory.Options options, ImageSize imageSize) {
    int width = options.outWidth;
    int height = options.outHeight;
    int inSampleSize = 1;

    if (width > imageSize.width || height > imageSize.height) {
        int widthRadio = Math.round(width * 1.0f / imageSize.width);
        int heightRadio = Math.round(height * 1.0f / imageSize.height);
        inSampleSize = Math.max(widthRadio, heightRadio);
    }
    return inSampleSize;
}

/** 把圖片放入 LruCache */
private void addBitmapToLruCache(Bitmap bitmap, String path) {
    if (getBitmapFromLruCache(path) == null) {
        if (bitmap != null) {
            mLruCache.put(path, bitmap);
        }
    }
}

/** 從 LruCache 取出圖片 */
private Bitmap getBitmapFromLruCache(String key) {
    return mLruCache.get(key);
}

至此,ImageLoader 的定義就完成了。

⑥ 在 MainActivity 中掃描手機圖片

private void initData() {
    // 透過 ContentProvider 掃描手機中的照片
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "當前儲存卡不可用", Toast.LENGTH_SHORT).show();
        return;
    }

    new Thread() {
        @Override
        public void run() {
            Uri mUriImg = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver contentResolver = MainActivity.this.getContentResolver();

            String selection = MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=?";
            String[] selectionArgs = new String[]{"image/jpeg", "image/png"};
            String sortOrder = MediaStore.Images.Media.DATE_MODIFIED;

            Cursor cursor = contentResolver.query(mUriImg, null, selection, selectionArgs, sortOrder);

            // 記錄已遍歷過的父目錄,避免重複處理
            Set<String> dirPaths = new HashSet<String>();
            FolderBean bean = null;

            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                File parentFile = new File(path).getParentFile();
                if (parentFile == null) {
                    continue;
                }
                String parentPath = parentFile.getAbsolutePath();
                if (dirPaths.contains(parentPath)) {
                    continue;
                }
                String[] imgNames = parentFile.list(mFilter);
                if (imgNames == null) {
                    continue;
                }
                dirPaths.add(parentPath);

                bean = new FolderBean();
                bean.setDirPath(parentPath);
                bean.setFirstImgPath(path);
                bean.setDirName(parentFile.getName());
                bean.setImgCount(imgNames.length);
                mFolderBeans.add(bean);
            }
            cursor.close();

            // 彙總成「所有圖片」
            bean = new FolderBean();
            bean.setDirName("所有圖片");
            bean.setFirstImgPath(mFolderBeans.get(0).getFirstImgPath());

            int imgCount = 0;
            String imgDirPath = "";
            for (FolderBean folderBean : mFolderBeans) {
                imgCount += folderBean.getImageCount();
                imgDirPath += folderBean.getDirPath() + SEPERATOR;
            }
            bean.setImgCount(imgCount);
            bean.setDirPath(imgDirPath.substring(0, imgDirPath.length() - 1));
            mFolderBeans.add(0, bean);

            initShowImgData(bean);   // 掃描完成,通知 Handler 更新介面

            Message msg = handler.obtainMessage();
            msg.what = MSG_DATA_LOADED;
            msg.obj = bean;
            handler.sendMessage(msg);
        }
    }.start();
}

設計要點小結

· 三級快取思路:先查記憶體中的 LruCache,未命中再丟進線程池從檔案讀取,讀完寫回緩存並刷新介面。
· 避免圖片錯亂:列表滚动時 View 會被復用,因此用 setTag(path) 記錄當前綁定的路徑,回呼時比對一致才設定圖片。
· 記憶體控制:緩存容量取最大可用記憶體的 1/8,並依 ImageView 實際尺寸動態計算 inSampleSize 做取樣。
· 調度策略:任務佇列採後進先出,滑到哪裡就先載入哪裡,讓使用者當前看得見的圖片優先完成。
· 線程同步:用兩個 Semaphore 分別解決 Handler 尚未建立就送訊息、以及線程池滿載時的阻塞問題。

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