开源框架Android-Universal-Image-Loader

Android-Universal-Image-Loader的github地址为:https://github.com/nostra13/Android-Universal-Image-Loader   正如他的github上的主页上的介绍:Powerful and flexible library for loading, caching and displaying images on Android.

Android-Universal-Image-Loader是用于Android的加载、缓存、展示图片功能强大、灵活的库。

UIL aims to provide a powerful, flexible and highly customizable instrument for image loading, caching and displaying. It provides a lot of configuration options and good control over the image loading and caching process.

Quick Setup

1. Include library
  • Download JAR
  • Put the JAR in the libs subfolder of your Android project
2. Android Manifest
<manifest>
    <!-- Include following permission if you load images from Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Include following permission if you want to cache images on SD card -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
3. Application or Activity class (before the first usage of ImageLoader)
public class MyActivity extends Activity {
    @Override
    public void onCreate() {
        super.onCreate();

        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
            ...
            .build();
        ImageLoader.getInstance().init(config);
        ...
    }
}

Configuration

ImageLoader Configuration (ImageLoaderConfiguration) is global for application. You should set it once.

All options in Configuration builder are optional. Use only those you really want to customize.
See default values for config options in Java docs for every option.

// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
        .diskCacheExtraOptions(480, 800, null)
        .taskExecutor(...)
        .taskExecutorForCachedImages(...)
        .threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 2) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .denyCacheImageMultipleSizesInMemory()
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
        .memoryCacheSize(2 * 1024 * 1024)
        .memoryCacheSizePercentage(13) // default
        .diskCache(new UnlimitedDiscCache(cacheDir)) // default
        .diskCacheSize(50 * 1024 * 1024)
        .diskCacheFileCount(100)
        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
        .imageDownloader(new BaseImageDownloader(context)) // default
        .imageDecoder(new BaseImageDecoder()) // default
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
        .writeDebugLogs()
        .build();

Display Options

Display Options (DisplayImageOptions) are local for every display task (ImageLoader.displayImage(...)).

Display Options can be applied to every display task (ImageLoader.displayImage(...)call).

Note: If Display Options wasn't passed to ImageLoader.displayImage(...)method then default Display Options from configuration (ImageLoaderConfiguration.defaultDisplayImageOptions(...)) will be used.

// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_stub) // resource or drawable
        .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
        .showImageOnFail(R.drawable.ic_error) // resource or drawable
        .resetViewBeforeLoading(false)  // default
        .delayBeforeLoading(1000)
        .cacheInMemory(false) // default
        .cacheOnDisk(false) // default
        .preProcessor(...)
        .postProcessor(...)
        .extraForDownloader(...)
        .considerExifParams(false) // default
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
        .bitmapConfig(Bitmap.Config.ARGB_8888) // default
        .decodingOptions(...)
        .displayer(new SimpleBitmapDisplayer()) // default
        .handler(new Handler()) // default
        .build();

Useful Info

  1. Caching is NOT enabled by default. If you want loaded images will be cached in memory and/or on disk then you should enable caching in DisplayImageOptions this way:

    // 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(true)
            .cacheOnDisk(true)
            ...
            .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

    or this way:

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            ...
            .cacheInMemory(true)
            .cacheOnDisk(true)
            ...
            .build();
    ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used
  2. If you enabled disk caching then UIL try to cache images on external storage (/sdcard/Android/data/[package_name]/cache). If external storage is not available then images are cached on device's filesystem. To provide caching on external storage (SD card) add following permission to AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
  3. How UIL define Bitmap size needed for exact ImageView? It searches defined parameters:

    • Get actual measured width and height of ImageView
    • Get android:layout_width and android:layout_height parameters
    • Get android:maxWidth and/or android:maxHeight parameters
    • Get maximum width and/or height parameters from configuration (memoryCacheExtraOptions(int, int) option)
    • Get width and/or height of device screen

    So try to set android:layout_width|android:layout_height orandroid:maxWidth|android:maxHeight parameters for ImageView if you know approximate maximum size of it. It will help correctly compute Bitmap size needed for this view and save memory.

  4. If you often got OutOfMemoryError in your app using Universal Image Loader then:

    • Disable caching in memory. If OOM is still occurs then it seems your app has a memory leak. Use MemoryAnalyzer to detect it. Otherwise try the following steps (all of them or several):
    • Reduce thread pool size in configuration (.threadPoolSize(...)). 1 - 5 is recommended.
    • Use .bitmapConfig(Bitmap.Config.RGB_565) in display options. Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
    • Use .imageScaleType(ImageScaleType.EXACTLY)
    • Use .diskCacheExtraOptions(480, 320, null) in configuration
  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
    • 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)
      • 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 disk cache configuration (ImageLoaderConfiguration.diskCache(...)) you can use already prepared implementations:

    • UnlimitedDiscCache (The fastest cache, doesn't limit cache size) - Used by default
    • LruDiskCache (Cache limited by total cache size and/or by file count. If cache size exceeds specified limit then least-recently used file will be deleted)
    • 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 pretty faster than other limited disk 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);
  9. If you see in logs some strange supplement at the end of image URL (e.g.http://anysite.com/images/image.png_230x460) then it doesn't mean this URL is used in requests. This is just "URL + target size", also this is key for Bitmap in memory cache. This postfix (_230x460) is NOT used in requests.

  10. ImageLoader always keeps aspect ratio of images.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值