編輯:關於 Android 程式設計
市面上優秀的圖片加載框架不少:UIL、Volley、Picasso、Fresco……但作為工程師,理解背後原理才算真正掌握。本文帶你從零打造一個能同時載入網路與本地圖片的框架,重點放在三件事:不 OOM、載入夠快、使用夠簡單。
目標一:記憶體不能爆。現在手機照片动辄幾千萬像素,直接塞進記憶體必死無疑。解法是用 LruCache 統一管理所有圖片,確保快取總量不超過預設上限。
目標二:載入順序要聰明。當使用者快速滑到第三千張,如果你還在從第一張慢慢載入,體驗就非常糟。因此不能採用先進先出(FIFO),而要用後進先出(LIFO)——優先載入使用者當前正在看的。
目標三:呼叫要簡單。一般圖片都用 GridView 呈現,在 getView 中載入。理想的 API 應該只需一行 loadImage(imageView, path),其餘交給框架處理,不必讓使用者自己 setTag、自己寫回呼。
本地圖片的效果可參考 Android 高仿微信圖片選擇器相關的 Demo。以下是一個網路圖片載入的示範:

八十多張網路圖片,直接拖到最後一格,出現在眼前的順序就是最新的——而不是從第一張開始排隊。示範圖片來源為部落格作者的分享,特此致謝。
不論網路或本地,載入前都必須先壓縮。呼叫方給我們一個 ImageView 與一個路徑,我們的職責就是「壓縮完再貼上去」。
沒有目標尺寸就無從壓縮起。取得方式依序降級:
/**
* 依據 ImageView 取得合適的壓縮寬高
*/
public static ImageSize getImageViewSize(ImageView imageView) {
ImageSize imageSize = new ImageSize();
DisplayMetrics displayMetrics = imageView.getContext()
.getResources().getDisplayMetrics();
LayoutParams lp = imageView.getLayoutParams();
int width = imageView.getWidth(); // 實際寬度
if (width <= 0) {
width = lp.width; // 布局中宣告的寬度
}
if (width <= 0) {
width = getImageViewFieldValue(imageView, mMaxWidth); // 最大值
}
if (width <= 0) {
width = displayMetrics.widthPixels; // 最終方案:螢幕寬度
}
int height = imageView.getHeight();
if (height <= 0) {
height = lp.height;
}
if (height <= 0) {
height = getImageViewFieldValue(imageView, mMaxHeight);
}
if (height <= 0) {
height = displayMetrics.heightPixels;
}
imageSize.width = width;
imageSize.height = height;
return imageSize;
}
public static class ImageSize {
int width;
int height;
}
這裡刻意用反射去讀 maxWidth/maxHeight,而不是呼叫 getMaxWidth()——因為該方法是 API 16 才有的,為了向下相容只能反射。
有了目標尺寸,接著要先知道圖片的真實尺寸。關鍵是 inJustDecodeBounds = true,它只讀取檔案標頭中的尺寸資訊,不會把像素載入記憶體:
// 只取寬高,不載入圖片 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options);
接著就能算出合適的取樣率:
/**
* 依需求寬高與圖片實際寬高計算 inSampleSize
*/
public static int caculateInSampleSize(Options options,
int reqWidth, int reqHeight) {
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
if (width > reqWidth || height > reqHeight) {
int widthRadio = Math.round(width * 1.0f / reqWidth);
int heightRadio = Math.round(height * 1.0f / reqHeight);
inSampleSize = Math.max(widthRadio, heightRadio);
}
return inSampleSize;
}
最後用這個值再解一次,壓縮就完成了:
options.inSampleSize = ImageSizeUtil.caculateInSampleSize(
options, width, height);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;
有兩條路。第一條是先下載存檔,再走本地壓縮流程——這適用於開啟硬碟快取的情況。第二條是直接串流解碼:
/**
* 依 URL 下載並壓縮圖片
*/
public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview) {
InputStream is = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(conn.getInputStream());
is.mark(is.available());
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opts);
// 取得 ImageView 期望的顯示尺寸
ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);
opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(
opts, imageViewSize.width, imageViewSize.height);
opts.inJustDecodeBounds = false;
is.reset(); // 回到起點,才能第二次解碼
Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
conn.disconnect();
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// ignore
}
}
}
return null;
}
注意一個細節:InputStream 必須先 mark() 才能 reset(),否則第二次解碼會拿到空資料。直接回傳的串流是不能重複使用的。
有了壓縮能力,接下來是整體結構。四個組成部分:
1. 單例 + LruCache:統一管理記憶體快取,key 用圖片路徑,value 是 Bitmap。
2. 任務隊列:每次載入請求都封裝成一個 Runnable 放進 TaskQueue。
3. 後台輪詢執行緒 + 執行緒池:後台執行緒在首次初始化時啟動並持續運行;每來一次請求就發一個訊息給它,它再從 TaskQueue 取任務交給執行緒池執行。
4. 調度策略:取任務時可選 FIFO 或 LIFO,這裡採用 LIFO。
public class ImageLoader {
private static ImageLoader mInstance;
/** 圖片快取的核心物件 */
private LruCache<String, Bitmap> mLruCache;
/** 執行緒池 */
private ExecutorService mThreadPool;
/** 隊列調度方式 */
private Type mType = Type.LIFO;
/** 任務隊列 */
private LinkedList<Runnable> mTaskQueue;
/** 後台輪詢執行緒 */
private Thread mPoolThread;
private Handler mPoolThreadHandler;
/** UI 執行緒中的 Handler */
private Handler mUIHandler;
private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0);
private Semaphore mSemaphoreThreadPool;
private boolean isDiskCacheEnable = true;
public enum Type { FIFO, LIFO }
public static ImageLoader getInstance(int threadCount, Type type) {
if (mInstance == null) {
synchronized (ImageLoader.class) {
if (mInstance == null) {
mInstance = new ImageLoader(threadCount, type);
}
}
}
return mInstance;
}
private ImageLoader(int threadCount, Type type) {
init(threadCount, type);
}
private void init(int threadCount, Type type) {
initBackThread();
// 取應用可用的最大記憶體,用 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 value) {
return value.getRowBytes() * value.getHeight();
}
};
mThreadPool = Executors.newFixedThreadPool(threadCount);
mTaskQueue = new LinkedList<Runnable>();
mType = type;
mSemaphoreThreadPool = new Semaphore(threadCount);
}
/** 初始化後台輪詢執行緒 */
private void initBackThread() {
mPoolThread = new Thread() {
@Override
public void run() {
Looper.prepare();
mPoolThreadHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 執行緒池取出一個任務執行
mThreadPool.execute(getTask());
try {
mSemaphoreThreadPool.acquire();
} catch (InterruptedException e) {
// ignore
}
}
};
// 通知等待中的呼叫方:Handler 已就緒
mSemaphorePoolThreadHandler.release();
Looper.loop();
}
};
mPoolThread.start();
}
}
/**
* 為 ImageView 依路徑設定圖片
*/
public void loadImage(final String path, final ImageView imageView,
final boolean isFromNet) {
// 用 tag 記錄「這個 ImageView 目前應該顯示哪張圖」
imageView.setTag(path);
if (mUIHandler == null) {
mUIHandler = new Handler() {
public void handleMessage(Message msg) {
ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
Bitmap bm = holder.bitmap;
ImageView imageview = holder.imageView;
String path = holder.path;
// 必須比對 tag,否則快速捲動時會出現圖片錯亂
if (imageview.getTag().toString().equals(path)) {
imageview.setImageBitmap(bm);
}
}
};
}
Bitmap bm = getBitmapFromLruCache(path);
if (bm != null) {
refreashBitmap(path, imageView, bm);
} else {
addTask(buildTask(path, imageView, isFromNet));
}
}
private void refreashBitmap(final String path, final ImageView imageView,
Bitmap bm) {
Message message = Message.obtain();
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = bm;
holder.path = path;
holder.imageView = imageView;
message.obj = holder;
mUIHandler.sendMessage(message);
}
那個 tag 比對是整個框架最容易被忽略卻最關鍵的一行。ListView/GridView 的 convertView 會被反覆重用,如果圖片載入完成時不檢查「這個 ImageView 現在想要的還是這張圖嗎」,就會出現滑動後圖片互相亂竄的經典 bug。
private synchronized void addTask(Runnable runnable) {
mTaskQueue.add(runnable);
try {
if (mPoolThreadHandler == null) {
mSemaphorePoolThreadHandler.acquire();
}
} catch (InterruptedException e) {
// ignore
}
mPoolThreadHandler.sendEmptyMessage(0x110);
}
/**
* 從任務隊列取出一個任務
*/
private Runnable getTask() {
if (mType == Type.FIFO) {
return mTaskQueue.removeFirst();
} else if (mType == Type.LIFO) {
return mTaskQueue.removeLast();
}
return null;
}
/**
* 依傳入參數建立一個載入任務
*/
private Runnable buildTask(final String path, final ImageView imageView,
final boolean isFromNet) {
return new Runnable() {
@Override
public void run() {
Bitmap bm = null;
if (isFromNet) {
File file = getDiskCacheDir(imageView.getContext(),
md5(path));
if (file.exists()) {
// 硬碟快取命中
bm = loadImageFromLocal(file.getAbsolutePath(), imageView);
} else {
if (isDiskCacheEnable) {
boolean downloadState = DownloadImgUtils
.downloadImgByUrl(path, file);
if (downloadState) {
bm = loadImageFromLocal(
file.getAbsolutePath(), imageView);
}
} else {
// 未開啟硬碟快取,直接從網路取
bm = DownloadImgUtils.downloadImgByUrl(path, imageView);
}
}
} else {
bm = loadImageFromLocal(path, imageView);
}
// 加入快取並回呼顯示
addBitmapToLruCache(path, bm);
refreashBitmap(path, imageView, bm);
mSemaphoreThreadPool.release();
}
};
}
private Bitmap loadImageFromLocal(final String path,
final ImageView imageView) {
// 1. 取得需要顯示的尺寸
ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView);
// 2. 依尺寸壓縮解碼
return decodeSampledBitmapFromPath(path,
imageSize.width, imageSize.height);
}
protected void addBitmapToLruCache(String path, Bitmap bm) {
if (getBitmapFromLruCache(path) == null && bm != null) {
mLruCache.put(path, bm);
}
}
程式碼中有兩處 Semaphore,都不是多餘的:
mSemaphorePoolThreadHandler = new Semaphore(0):用來確保 mPoolThreadHandler 已完成初始化。因為後台執行緒與主執行緒啟動時序不確定,若主執行緒先呼叫 addTask 而 Handler 還是 null,就會出錯。這裡的做法是:Handler 為 null 時用 acquire() 阻塞,等後台執行緒建立好 Handler 後呼叫 release() 解除阻塞。
mSemaphoreThreadPool = new Semaphore(threadCount):數量與載入執行緒數一致。每取一個任務執行就減一,任務完成後加一再去取下一個。目的是:只有當有執行緒空閒時才取任務。若無條件狂取任務,隊列裡的舊任務會被瞬間消耗完,LIFO 策略就失去意義了。這也是「優先載入當前可見項」能夠真正生效的前提。
快取檔案的位置在 SD 卡的 Android/data/專案packageName/cache 目錄下:

呼叫端非常簡單,在 getView 中一行搞定:
public class ListImgsFragment extends Fragment {
private GridView mGridView;
private String[] mUrlStrs = Images.imageThumbUrls;
private ImageLoader mImageLoader;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 3 條執行緒,LIFO 策略
mImageLoader = ImageLoader.getInstance(3, Type.LIFO);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_imgs,
container, false);
mGridView = (GridView) view.findViewById(R.id.id_gridview);
setUpAdapter();
return view;
}
private void setUpAdapter() {
if (getActivity() == null || mGridView == null) {
return;
}
if (mUrlStrs != null) {
mGridView.setAdapter(
new ListImgItemAdaper(getActivity(), 0, mUrlStrs));
} else {
mGridView.setAdapter(null);
}
}
private class ListImgItemAdaper extends ArrayAdapter<String> {
public ListImgItemAdaper(Context context, int resource, String[] datas) {
super(getActivity(), 0, datas);
}
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.item_fragment_list_imgs,
parent, false);
}
ImageView imageview = (ImageView)
convertView.findViewById(R.id.id_img);
imageview.setImageResource(R.drawable.pictures_no);
mImageLoader.loadImage(getItem(position), imageview, true);
return convertView;
}
}
}
配套的兩個布局:
<!-- fragment_list_imgs.xml -->
<GridView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/id_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="3dp"
android:verticalSpacing="3dp" />
<!-- item_fragment_list_imgs.xml -->
<ImageView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/id_img"
android:layout_width="match_parent"
android:layout_height="120dp"
android:scaleType="centerCrop" />
這個框架已經能跑,但若要 production 級別,建議再補上幾件事:三級快取同步(記憶體 → 硬碟 → 網路)的雙向更新要更嚴謹;執行緒池要支援任務取消,滑走的項目應該從隊列中移除而不是照樣下載;圖片加載失敗要有重試與降級策略;硬碟快取要做 LRU 淘汰與容量上限,否則長期使用會塞滿儲存空間。另外,若專案 minSdk 允許,直接採用 Glide 或 Coil 這類成熟方案,把力氣花在業務上會更划算——但自己寫過一遍,除錯與調優時才有底氣。
Android 筆記 - Binder 之請求注冊 Service 組件
Android 系統大量採用了組件化的設計思路,將眾多核心服務以 Service 組件的形式對外提供。Service 只有注冊到 servicemanager 後,Cli
安卓 APK 瘦身實戰:把安裝包砍掉四分之一
以前打包就是 Eclipse 或 Android Studio 直接生成簽名文件,從沒關注過體積問題。直到有人問我「你有做過 APK 瘦身嗎」,才發現這塊一直是空白。折騰
Key-Value Observing(鍵值監測 KVO)完全指南
簡介 KVO 是一套當目標對象的屬性值改變時,觀察者能收到通知的機制。想真正理解 KVO,得先搞懂 KVC,因為前者是後者的實現基礎。這種通信機制在 MVC 設計模式中十
基於 Android 實現圖片平移、縮放與旋轉同時進行
前言 之前因為專案需求,用到了圖片的單擊顯示/取消與平移縮放功能,昨天突然想再加上圖片旋轉,於是上網看了很多相關例子,卻始終沒找到能同時實現我想要的全部功能的。 需求: