ListView GridView ViewPager 異步 加載網絡圖片 緩存到本地

Android-Universal-Image-Loader

Github地址:Android-Universal-Image-Loader 萬能的圖片加載器!
作者:nostra13


特性

  • 多線程圖片加載
  • 儘可能多的配置選項(線程池,加載器,解析器,內存/磁盤緩存,顯示參數等等)
  • 圖片可以緩存在內存中,或者設備文件目錄下,或者SD卡中
  • 可以監聽加載進度
  • 可以自定義顯示每一張圖片時都帶不同參數
  • 支持Widget

Quick Setup

1.Include library

下載連接 JAR

核心Jar包已經上傳地址:http://download.csdn.net/detail/zabio/6956555

2.Android Manifest

<manifest>
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Include next permission if you want to allow UIL to cache images on SD card -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
    <application android:name="MyApplication">
        ...
    </application>
</manifest>

3. Application class

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Create global configuration and initialize ImageLoader with this configuration
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            ...
            .build();
        ImageLoader.getInstance().init(config);
    }
}

Configuration and Display Options

  • Configuration(ImageLoaderConfiguration) 是相對於整個應用的配置
  • Display Options(DisplayImageOptions)是針對每一個顯示圖片任務所提供的參數(ImageLoader.displayImage(…)).

Configuration

所有的選項都是可選的,只選擇你真正想制定的去配置。

// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        //如果圖片尺寸大於了這個參數,那麼就會這按照這個參數對圖片大小進行限制並緩存
        .memoryCacheExtraOptions(480, 800) // default=device screen dimensions
        .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75)
        .taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
        .taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
        .threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 1) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .denyCacheImageMultipleSizesInMemory()
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
        .memoryCacheSize(2 * 1024 * 1024)
        .discCache(new UnlimitedDiscCache(cacheDir)) // default
        .discCacheSize(50 * 1024 * 1024)
        .discCacheFileCount(100)
        .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
        .imageDownloader(new BaseImageDownloader(context)) // default
        .imageDecoder(new BaseImageDecoder()) // default
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
        .enableLogging()
        .build();

參數主要包括了這麼幾類配置 1. 線程池配置 2. 內存緩存配置 3. 磁盤緩存配置 4. 使用哪個圖片下載器 5. 使用哪個圖片解析器 實際上,不做任何配置也是ImageLoader也是可以使用的。 插一句,配置選項的確夠豐富,但有多是沒有必要的。

Display Options

顯示參數可以分別被每一個顯示任務調用(ImageLoader.displayImage(…))

Note:如果沒有調用ImageLoader.displayImage(…),那麼將使用配置選項中的默認顯示參數(ImageLoaderConfiguration.defaultDisplayImageOptions(…))

DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showStubImage(R.drawable.ic_stub)  // 在顯示真正的圖片前,會加載這個資源
        .showImageForEmptyUri(R.drawable.ic_empty) //空的Url時
        .showImageOnFail(R.drawable.ic_error) 
        .resetViewBeforeLoading() // 
        .delayBeforeLoading(1000)     // 延長1000ms 加載圖片  (想不出來用在什麼場景下)
        .cacheInMemory()              
        .cacheOnDisc()               
        .preProcessor(...)            
        .postProcessor(...)           
        .extraForDownloader(...)      //可以向加載器攜帶一些參數 
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default  
        .bitmapConfig(Bitmap.Config.ARGB_8888) // default
        .decodingOptions(...)
        .displayer(new SimpleBitmapDisplayer()) // default
        .handler(new Handler()) // default
        .build();

用法

可接收的URL

String imageUri = "http://site.com/image.png"; // from Web
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
String imageUri = "content://media/external/audio/albumart/13"; // from content provider
String imageUri = "assets://image.png"; // from assets
String imageUri = "drawable://" + R.drawable.image; // from drawables (only imag
es, non-9patch)

例子

// Load image, decode it to Bitmap and display Bitmap in ImageView
imageLoader.displayImage(imageUri, imageView);
// Load image, decode it to Bitmap and return Bitmap to callback
imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        // Do whatever you want with Bitmap
    }
});

完整版

// Load image, decode it to Bitmap and display Bitmap in ImageView
imageLoader.displayImage(imageUri, imageView, displayOptions, new ImageLoadingListener() {
    @Override
    public void onLoadingStarted(String imageUri, View view) {
        ...
    }
    @Override
    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
        ...
    }
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        ...
    }
    @Override
    public void onLoadingCancelled(String imageUri, View view) {
        ...
    }
});
ImageSize targetSize = new ImageSize(120, 80); // result Bitmap will be fit to this size
imageLoader.loadImage(imageUri, targetSize, displayOptions, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        // Do whatever you want with Bitmap
    }
});

ImageLoader Helpers

一些可能會用到的幫助類和方法

ImageLoader |
            | - getMemoryCache()
            | - clearMemoryCache()
            | - getDiscCache()
            | - clearDiscCache()
            | - denyNetworkDownloads(boolean)
            | - handleSlowNetwork(boolean)
            | - pause()
            | - resume()
            | - stop()
            | - destroy()
            | - getLoadingUriForView(ImageView)
            | - cancelDisplayTask(ImageView)
MemoryCacheUtil |
                | - findCachedBitmapsForImageUri(...)
                | - findCacheKeysForImageUri(...)
                | - removeFromCache(...)
DiscCacheUtil |
              | - findInCache(...)
              | - removeFromCache(...)
StorageUtils |
             | - getCacheDirectory(Context)
             | - getIndividualCacheDirectory(Context)
             | - getOwnCacheDirectory(Context, String)
PauseOnScrollListener

Useful Info

1.使用默認值時緩存無效。如果你想要加載圖片的時候使用內存/磁盤中的緩存,那麼你應該這樣設置DisplayImageOptions:

// Create default options which will be used for every 
//  displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
        ...
        .cacheInMemory()
        .cacheOnDisc()
        ...
        .build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
        ...
        .defaultDisplayImageOptions(defaultOptions)
        ...
        .build();
ImageLoader.getInstance().init(config); // Do it on Application start
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used

或者這樣:

DisplayImageOptions options = new DisplayImageOptions.Builder()
        ...
        .cacheInMemory()
        .cacheOnDisc()
        ...
        .build();
ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used

2.如果你允許緩存在磁盤中,那麼UIL將嘗試緩存到(/sdcard/Android/data/[package_name]/cache)路徑中。如果外部存儲不可用的話,圖片將緩存在設備文件系統下。爲了支持在外部存儲(SD card)中緩存,那麼應該在AndroidManifest.xml中加上這個權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

3.UIL如果知道Bitmap應該有多大的尺寸放在確定了點ImageView中?它搜索以下幾個定義的參數:

  • 從ImageView測量準確的高和寬獲得
  • 從android:layoutwidth 和 android:layoutheight 參數獲得
  • 從 android:maxWidth 和/或者 android:maxHeight 參數獲得
  • 從在configuration定義的maximun width 和/或者 height參數獲得
  • 從設備屏幕 width 和/或者 height 獲得

If you often got OutOfMemoryError in your app using Universal Image Loader then try next (all of them or several):

  • Reduce thread pool size in configuration (.threadPoolSize(...)). 1 - 5 is recommended.
  • Use .bitmapConfig(Bitmap.Config.RGB565) in display options. Bitmaps in RGB565 consume 2 times less memory than in ARGB_8888.
  • Use .memoryCache(new WeakMemoryCache()) in configuration or disable caching in memory at all in display options (don't call .cacheInMemory()).
  • Use .imageScaleType(ImageScaleType.INSAMPLEINT) in display options. Or try .imageScaleType(ImageScaleType.EXACTLY).
  • Avoid using RoundedBitmapDisplayer. It creates new Bitmap object with ARGB_8888 config for displaying during work.

5.For memory cache configuration (ImageLoaderConfiguration.memoryCache(...)) you can use already prepared implementations.

  • Cache using only strong references: LruMemoryCache (Least recently used bitmap is deleted when cache size limit is exceeded) - Used by default for API >= 9
  • Caches using weak and strong references: UsingFreqLimitedMemoryCache (Least frequently used bitmap is deleted when cache size limit is exceeded) LRULimitedMemoryCache (Least recently used bitmap is deleted when cache size limit is exceeded) - Used by default for API < 9 FIFOLimitedMemoryCache (FIFO rule is used for deletion when cache size limit is exceeded) LargestLimitedMemoryCache (The largest bitmap is deleted when cache size limit is exceeded) LimitedAgeMemoryCache (Decorator. Cached object is deleted when its age exceeds defined value)
  • Cache using only weak references: WeakMemoryCache (Unlimited cache)

6.For disc cache configuration (ImageLoaderConfiguration.discCache(...)) you can use already prepared implementations:

  • UnlimitedDiscCache (The fastest cache, doesn't limit cache size) - Used by default
  • TotalSizeLimitedDiscCache (Cache limited by total cache size. If cache size exceeds specified limit then file with the most oldest last usage date will be deleted)
  • FileCountLimitedDiscCache (Cache limited by file count. If file count in cache directory exceeds specified limit then file with the most oldest last usage date will be deleted. Use it if your cached files are of about the same size.)
  • LimitedAgeDiscCache (Size-unlimited cache with limited files' lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.) NOTE: UnlimitedDiscCache is 30%-faster than other limited disc cache implementations.

7.To display bitmap (DisplayImageOptions.displayer(...)) you can use already prepared implementations: - RoundedBitmapDisplayer (Displays bitmap with rounded corners) - FadeInBitmapDisplayer (Displays image with "fade in" animation)

8.To avoid list (grid, ...) scrolling lags you can use PauseOnScrollListener:

boolean pauseOnScroll = false; // or true
boolean pauseOnFling = true; // or false
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
listView.setOnScrollListener(listener);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章