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

Universal Image Loader 圖片緩存與使用完整指南

編輯:關於 Android 程式設計

在 Android 上處理網路圖片一向麻煩:下載、解碼、顯示、回收,任一環節出錯就可能 OOM。Universal Image Loader(UIL)就是為了解決這一整串問題而生,它源自 Fedor Vlasov 的專案,經過大幅重構後成為 GitHub 上相當知名的開源庫。

它提供了什麼

  • 多執行緒下載,來源可以是網路、本機檔案、assets 或 drawable。
  • 高度可配置的 ImageLoader:執行緒池、下載器、記憶體與磁碟緩存策略、顯示選項等。
  • 支援記憶體緩存、檔案系統緩存與 SD 卡緩存。
  • 可監聽下載與載入過程。
  • 依 ImageView 實際尺寸裁切 Bitmap,避免佔用過多記憶體。
  • 可暫停/恢復載入,常用於 ListView、GridView 滑動時的效能優化。
  • 針對慢網路有相應處理。

最簡單的初始化

ImageLoader 是單例,用 getInstance() 取得。使用前必須先初始化設定,否則會丟出 IllegalStateException:

 //創建默認的ImageLoader配置參數 ImageLoaderConfiguration configuration = ImageLoaderConfiguration .createDefault(this); //Initialize ImageLoader with configuration. ImageLoader.getInstance().init(configuration); 

自訂配置

因為是單例,整個 App 只需初始化一次,建議放在 Application 或第一個 Activity 的 onCreate 中;重複初始化不會有效果。透過 ImageLoaderConfiguration.Builder 可以細調各項參數:

 File cacheDir =StorageUtils.getOwnCacheDirectory(this, "imageloader/Cache"); ImageLoaderConfigurationconfig = new ImageLoaderConfiguration .Builder(this) .memoryCacheExtraOptions(480, 800) // maxwidth, max height,即保存的每個緩存文件的最大長寬 .threadPoolSize(3)//線程池內加載的數量 .threadPriority(Thread.NORM_PRIORITY -2) .denyCacheImageMultipleSizesInMemory() .memoryCache(new UsingFreqLimitedMemoryCache(2* 1024 * 1024)) // You can pass your own memory cache implementation/你可以通過自己的內存緩存實現 .memoryCacheSize(2 * 1024 * 1024) .discCacheSize(50 * 1024 * 1024) .discCacheFileNameGenerator(newMd5FileNameGenerator())//將保存的時候的URI名稱用MD5 加密 .tasksProcessingOrder(QueueProcessingType.LIFO) .discCacheFileCount(100) //緩存的文件數量 .discCache(new UnlimitedDiscCache(cacheDir))//自定義緩存路徑 .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) .imageDownloader(new BaseImageDownloader(this,5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超時時間 .writeDebugLogs() // Remove for releaseapp .build();//開始構建 ImageLoader.getInstance().init(config); 

實務上要特別注意 threadPoolSize:設太大反而增加 OOM 風險,官方建議落在 1 到 5 之間。memoryCacheExtraOptions 則是用來告訴 UIL 你的 ImageView 大概會有多大,讓它預留合理的解碼緩衝。

取得實例並顯示圖片

 ImageLoader imageLoader = ImageLoader.getInstance();

顯示前先建立 DisplayImageOptions,決定載入中、失敗、空 URI 時的佔位圖,以及是否啟用雙緩存:

 DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) //加載圖片時的圖片 .showImageForEmptyUri(R.drawable.ic_empty) //沒有圖片資源時的默認圖片 .showImageOnFail(R.drawable.ic_error) //加載失敗時的圖片 .cacheInMemory(true) //啟用內存緩存 .cacheOnDisk(true) //啟用外存緩存 .considerExifParams(true) //啟用EXIF和JPEG圖像格式 .displayer(new RoundedBitmapDisplayer(20)) //設置顯示風格這裡是圓角矩形 .build(); 

以下是 DisplayImageOptions 全部的預設欄位,可依需求自行覆寫:

 private int imageResOnLoading = 0; private int imageResForEmptyUri = 0; private int imageResOnFail = 0; private Drawable imageOnLoading = null; private Drawable imageForEmptyUri = null; private Drawable imageOnFail = null; private boolean resetViewBeforeLoading = false; private boolean cacheInMemory = false; private boolean cacheOnDisk = false; private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2; private Options decodingOptions = new Options(); private int delayBeforeLoading = 0; private boolean considerExifParams = false; private Object extraForDownloader = null; private BitmapProcessor preProcessor = null; private BitmapProcessor postProcessor = null; private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer(); private Handler handler = null; private boolean isSyncLoading = false; 

載入過程的監聽與動畫

想加上淡入效果或進度條,就實作 ImageLoadingListener。下面這個寫法用一個靜態清單記住哪些 URI 已經播放過動畫,避免捲動時重複閃動:

 ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener { static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); displayedImages.add(imageUri); } } } }

然後一行就能載入:

 imageLoader.displayImage(imageUrl, imageview, options, animateFirstListener);

本地圖片要在絕對路徑前加上 file://,網路圖片直接寫 URL。不同來源的寫法如下:

 String imageUri = "https://site.com/image.png"; // 網絡圖片 String imageUri = "file:///mnt/sdcard/image.png"; //SD卡圖片 String imageUri = "content://media/external/audio/albumart/13"; // 媒體文件夾 String imageUri = "assets://image.png"; // assets String imageUri = "drawable://" + R.drawable.image; // drawable文件 

清理緩存

可以放在 Activity 的 onDestroy,也可以做成設定頁讓使用者自行決定:

 @Override public void onDestroy() { super.onDestroy(); imageLoader.clearMemoryCache(); imageLoader.clearDiskCache(); }

ListView / GridView 的滑動優化

長列表快速滑動時,載入非當前畫面的圖片純屬浪費。UIL 提供了 PauseOnScrollListener,用代理模式攔住捲動事件:

 listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling)); gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling)); 

第一個參數是 ImageLoader,第二個控制「滑動中是否暫停」,第三個控制「快速甩動時是否暫停」。一般建議兩者都傳 true。

OOM 了怎麼辦

UIL 對 OutOfMemoryError 做了 catch,能避免直接 crash,但如果頻繁發生就該從設定下手:

  • 調小 threadPoolSize,建議 1 到 5。
  • 在 DisplayImageOptions 中把 bitmapConfig 設為 Bitmap.Config.RGB_565,相比預設的 ARGB_8888 可省下約一半記憶體(代價是沒有 alpha 通道)。
  • 改用 memoryCache(new WeakMemoryCache()) 或直接關閉記憶體緩存。
  • 調整 imageScaleType 為 IN_SAMPLE_INT 或 EXACTLY。

displayImage 與 loadImage 該選哪個

建議優先用 displayImage()。它對 ImageView 使用弱引用,方便 GC 回收,而且會依 ImageView 的測量值或 layout_width/height、maxWidth/maxHeight 自動裁切圖片。相對地,loadImage() 只是把 Bitmap 透過 onLoadingComplete() 回呼給你,需要自己 setImageBitmap,而且要明確傳入 ImageSize 才能控制解碼尺寸。除非你有特殊需求(例如預先下載但不立刻顯示),否則用 displayImage 更省心。

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