Android-Universal-Image-Loader-万能图片加载器

源博客文章链接:http://linkyan.com/2013/05/android-universal-image-loader/

Github地址:Android-Universal-Image-Loader 万能的图片加载器!

作者:nostra13

废话不多开始介绍

This project aims to provide a reusable instrument for asynchronous image loading, caching and displaying. It is originally based on Fedor Vlasov's project and has been vastly refactored and improved since then.

作者说他也是Fedor Vlasov's project这个项目改写过来的,做到对图片的异步加载,缓存和显示。

特性

  • 多线程图片加载
  • 尽可能多的配置选项(线程池,加载器,解析器,内存/磁盘缓存,显示参数等等)
  • 图片可以缓存在内存中,或者设备文件目录下,或者SD卡中
  • 可以监听加载进度
  • 可以自定义显示每一张图片时都带不同参数
  • 支持Widget

Quick Setup

1.Include library

下载连接 JAR

2.Android Manifest

1 <manifest>
2     <uses-permission android:name="android.permission.INTERNET" />
3     <!-- Include next permission if you want to allow UIL to cache images on SD card -->
4     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
5     ...
6     <application android:name="MyApplication">
7     ...
8     </application>
9 </manifest>

3. Application class

01 public class MyApplication extends Application {
02     @Override
03     public void onCreate() {
04         super.onCreate();
05         // Create global configuration and initialize ImageLoader with this configuration
06         ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
07             ...
08             .build();
09         ImageLoader.getInstance().init(config);
10     }
11 }

Configuration and Display Options

  • Configuration(ImageLoaderConfiguration) 是相对于整个应用的配置
  • Display Options(DisplayImageOptions)是针对每一个显示图片任务所提供的参数(ImageLoader.displayImage(…)).

Configuration

所有的选项都是可选的,只选择你真正想制定的去配置。

01 File cacheDir = StorageUtils.getCacheDirectory(context);
02 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
03     //如果图片尺寸大于了这个参数,那么就会这按照这个参数对图片大小进行限制并缓存
04     .memoryCacheExtraOptions(480800// default=device screen dimensions
05     .discCacheExtraOptions(480800, CompressFormat.JPEG, 75)
06     .taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
07     .taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
08     .threadPoolSize(3// default
09     .threadPriority(Thread.NORM_PRIORITY - 1// default
10     .tasksProcessingOrder(QueueProcessingType.FIFO) // default
11     .denyCacheImageMultipleSizesInMemory()
12     .memoryCache(new LruMemoryCache(2 1024 1024))
13     .memoryCacheSize(2 1024 1024)
14     .discCache(new UnlimitedDiscCache(cacheDir)) // default
15     .discCacheSize(50 1024 1024)
16     .discCacheFileCount(100)
17     .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
18     .imageDownloader(new BaseImageDownloader(context)) // default
19     .imageDecoder(new BaseImageDecoder()) // default
20     .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
21     .enableLogging()
22     .build();

参数主要包括了这么几类配置 1. 线程池配置 2. 内存缓存配置 3. 磁盘缓存配置 4. 使用哪个图片下载器 5. 使用哪个图片解析器 实际上,不做任何配置也是ImageLoader也是可以使用的。 插一句,配置选项的确够丰富,但有多是没有必要的。

Display Options

显示参数可以分别被每一个显示任务调用(ImageLoader.displayImage(…))

Note:如果没有调用ImageLoader.displayImage(…),那么将使用配置选项中的默认显示参数(ImageLoaderConfiguration.defaultDisplayImageOptions(…))

01 DisplayImageOptions options = new DisplayImageOptions.Builder()
02     .showStubImage(R.drawable.ic_stub)  // 在显示真正的图片前,会加载这个资源
03     .showImageForEmptyUri(R.drawable.ic_empty) //空的Url时
04     .showImageOnFail(R.drawable.ic_error)
05     .resetViewBeforeLoading() //
06     .delayBeforeLoading(1000)     // 延长1000ms 加载图片  (想不出来用在什么场景下)
07     .cacheInMemory()             
08     .cacheOnDisc()              
09     .preProcessor(...)           
10     .postProcessor(...)          
11     .extraForDownloader(...)      //可以向加载器携带一些参数
12     .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default 
13     .bitmapConfig(Bitmap.Config.ARGB_8888) // default
14     .decodingOptions(...)
15     .displayer(new SimpleBitmapDisplayer()) // default
16     .handler(new Handler()) // default
17     .build();

用法

可接收的URL

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

例子

01 // Load image, decode it to Bitmap and display Bitmap in ImageView
02 imageLoader.displayImage(imageUri, imageView);
03  
04 <!-- lang: java -->
05 // Load image, decode it to Bitmap and return Bitmap to callback
06 imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
07     @Override
08     public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
09         // Do whatever you want with Bitmap
10     }
11 });

完整版

01 // Load image, decode it to Bitmap and display Bitmap in ImageView
02 imageLoader.displayImage(imageUri, imageView, displayOptions,
03 new ImageLoadingListener() {
04     @Override
05     public void onLoadingStarted(String imageUri, View view) {
06         ...
07     }
08     @Override
09     public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
10         ...
11     }
12     @Override
13     public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
14         ...
15     }   
16     @Override
17     public void onLoadingCancelled(String imageUri, View view) {
18         ...
19     }
20 });
21  
22  
23  
24 ImageSize targetSize = new ImageSize(12080); // result Bitmap will be fit to this size
25 imageLoader.loadImage(imageUri, targetSize, displayOptions, new     SimpleImageLoadingListener() {
26     @Override
27     public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
28         // Do whatever you want with Bitmap
29     }
30 });

ImageLoader Helpers

一些可能会用到的帮助类和方法

01 ImageLoader |
02         | - getMemoryCache()
03         | - clearMemoryCache()
04         | - getDiscCache()
05         | - clearDiscCache()
06         | - denyNetworkDownloads(boolean)
07         | - handleSlowNetwork(boolean)
08         | - pause()
09         | - resume()
10         | - stop()
11         | - destroy()
12         | - getLoadingUriForView(ImageView)
13         | - cancelDisplayTask(ImageView)
14 MemoryCacheUtil |
15             | - findCachedBitmapsForImageUri(...)
16             | - findCacheKeysForImageUri(...)
17             | - removeFromCache(...)
18 DiscCacheUtil |
19           | - findInCache(...)
20           | - removeFromCache(...)
21 StorageUtils |
22          | - getCacheDirectory(Context)
23          | - getIndividualCacheDirectory(Context)
24          | - getOwnCacheDirectory(Context, String)
25 PauseOnScrollListener

Useful Info

1.使用默认值时缓存无效。如果你想要加载图片的时候使用内存/磁盘中的缓存,那么你应该这样设置DisplayImageOptions:

01 // Create default options which will be used for every
02 //  displayImage(...) call if no options will be passed to this method
03 DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
04     ...
05     .cacheInMemory()
06     .cacheOnDisc()
07     ...
08     .build();
09 ImageLoaderConfiguration config = new     ImageLoaderConfiguration.Builder(getApplicationContext())
10     ...
11     .defaultDisplayImageOptions(defaultOptions)
12     ...
13     .build();
14 ImageLoader.getInstance().init(config); // Do it on Application start
15  
16 <!-- lang: java -->
17 // Then later, when you want to display image
18 ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used

或者这样:

1 DisplayImageOptions options = new DisplayImageOptions.Builder()
2     ...
3     .cacheInMemory()
4     .cacheOnDisc()
5     ...
6     .build();
7 ImageLoader.getInstance().displayImage(imageUrl, imageView, options);
8 // Incoming options will be used

2.如果你允许缓存在磁盘中,那么UIL将尝试缓存到(/sdcard/Android/data/[package_name]/cache)路径中。如果外部存储不可用的话,图片将缓存在设备文件系统下。为了支持在外部存储(SD card)中缓存,那么应该在AndroidManifest.xml中加上这个权限:

1 <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:

1 boolean pauseOnScroll = false// or true
2 boolean pauseOnFling = true// or false
3 PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,     pauseOnScroll, pauseOnFling);
4 listView.setOnScrollListener(listener);

源博客文章链接:http://linkyan.com/2013/05/android-universal-image-loader/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值