萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android ListView 異步圖片加載框架設計:三級緩存與回調機制實戰

核心痛點

ListView 復用機制導致圖片錯位、閃爍;網絡圖片下載不可控阻塞 UI 線程;流量與內存雙重壓力。解決方案:異步加載 + 多級緩存 + 回調更新。

架構設計:AsyncBitmapLoader

三級緩存策略

  1. 內存緩存(L1):HashMap> — 命中即時返回,SoftReference 隨 GC 釋放,防 OOM。
  2. 本地磁盤緩存(L2):/mnt/sdcard/cache/ — 內存未命中時查找,命中則解碼返回並回填內存緩存。
  3. 網絡下載(L3):雙緩存均未命中,開啟子線程下載,完成後:
    • 解碼 Bitmap
    • 存入內存緩存
    • 寫入磁盤文件
    • 通過 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,由回調異步設置圖片
    }
}

ListView Adapter 中正確使用

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

生產級優化建議

  • 使用成熟庫:Glide / Picasso / Coil (Kotlin) — 自動處理生命周期、緩存策略、請求合併、變換、預加載。
  • 磁盤緩存用 DiskLruCache 實現 LRU 淘汰,限制容量。
  • 下載線程池配置核心數 = CPU 核心數 + 1,隊列有界。
  • 圖片解碼採用 inSampleSize 按需縮放,避免加載超大原圖。
  • 支援 pauseOnScroll 滑動暫停加載,preload 預加載可視區外圖片。
copyright © 萬盛學電腦網 all rights reserved