ListView 復用機制導致圖片錯位、閃爍;網絡圖片下載不可控阻塞 UI 線程;流量與內存雙重壓力。解決方案:異步加載 + 多級緩存 + 回調更新。
HashMap> — 命中即時返回,SoftReference 隨 GC 釋放,防 OOM。/mnt/sdcard/cache/ — 內存未命中時查找,命中則解碼返回並回填內存緩存。Handler 發送消息觸發回調public class AsyncBitmapLoader {
private HashMap> memoryCache = new HashMap<>();
private final String diskCacheDir = "/mnt/sdcard/test/";
public interface ImageCallback {
void onImageLoaded(ImageView imageView, Bitmap bitmap);
}
public Bitmap loadBitmap(ImageView imageView, String imageUrl, ImageCallback callback) {
// 1. 內存緩存命中
if (memoryCache.containsKey(imageUrl)) {
Bitmap bmp = memoryCache.get(imageUrl).get();
if (bmp != null) return bmp;
}
// 2. 磁盤緩存命中
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
File file = new File(diskCacheDir, fileName);
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bmp != null) {
memoryCache.put(imageUrl, new SoftReference<>(bmp));
return bmp;
}
}
// 3. 異步下載
final Handler handler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
callback.onImageLoaded(imageView, (Bitmap) msg.obj);
}
};
new Thread(() -> {
InputStream is = HttpUtils.getStreamFromURL(imageUrl);
Bitmap bitmap = BitmapFactory.decodeStream(is);
if (bitmap != null) {
memoryCache.put(imageUrl, new SoftReference<>(bitmap));
// 寫磁盤
File dir = new File(diskCacheDir);
if (!dir.exists()) dir.mkdirs();
try (FileOutputStream fos = new FileOutputStream(file)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (IOException ignored) {}
// 回調主線程
handler.sendMessage(handler.obtainMessage(0, bitmap));
}
}).start();
return null; // 異步模式返回 null,由回調異步設置圖片
}
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { /* inflate & findView */ }
holder.imageView.setImageResource(R.drawable.placeholder); // 佔位圖防閃爍
holder.imageView.setTag(imageUrl); // 標記防錯位
Bitmap cached = loader.loadBitmap(holder.imageView, imageUrl, (iv, bmp) -> {
if (imageUrl.equals(iv.getTag())) { // 雙重校驗防止列表滑動時圖片錯位
iv.setImageBitmap(bmp);
}
});
if (cached != null) holder.imageView.setImageBitmap(cached); // 同步命中直接設置
return convertView;
}
DiskLruCache 實現 LRU 淘汰,限制容量。inSampleSize 按需縮放,避免加載超大原圖。pauseOnScroll 滑動暫停加載,preload 預加載可視區外圖片。