源博客文章链接: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
2 | < uses-permission android:name = "android.permission.INTERNET" /> |
4 | < uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" /> |
6 | < application android:name = "MyApplication" > |
3. Application class
01 | public class MyApplication extends Application { |
03 | public void onCreate() { |
06 | ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) |
09 | ImageLoader.getInstance().init(config); |
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) |
04 | .memoryCacheExtraOptions( 480 , 800 ) |
05 | .discCacheExtraOptions( 480 , 800 , CompressFormat.JPEG, 75 ) |
06 | .taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR) |
07 | .taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR) |
09 | .threadPriority(Thread.NORM_PRIORITY - 1 ) |
10 | .tasksProcessingOrder(QueueProcessingType.FIFO) |
11 | .denyCacheImageMultipleSizesInMemory() |
12 | .memoryCache( new LruMemoryCache( 2 * 1024 * 1024 )) |
13 | .memoryCacheSize( 2 * 1024 * 1024 ) |
14 | .discCache( new UnlimitedDiscCache(cacheDir)) |
15 | .discCacheSize( 50 * 1024 * 1024 ) |
16 | .discCacheFileCount( 100 ) |
17 | .discCacheFileNameGenerator( new HashCodeFileNameGenerator()) |
18 | .imageDownloader( new BaseImageDownloader(context)) |
19 | .imageDecoder( new BaseImageDecoder()) |
20 | .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) |
参数主要包括了这么几类配置 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) |
04 | .showImageOnFail(R.drawable.ic_error) |
05 | .resetViewBeforeLoading() |
06 | .delayBeforeLoading( 1000 ) |
11 | .extraForDownloader(...) |
12 | .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) |
13 | .bitmapConfig(Bitmap.Config.ARGB_8888) |
15 | .displayer( new SimpleBitmapDisplayer()) |
16 | .handler( new Handler()) |
用法
可接收的URL
5 | String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch) |
例子
02 | imageLoader.displayImage(imageUri, imageView); |
06 | imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() { |
08 | public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { |
完整版
02 | imageLoader.displayImage(imageUri, imageView, displayOptions, |
03 | new ImageLoadingListener() { |
05 | public void onLoadingStarted(String imageUri, View view) { |
09 | public void onLoadingFailed(String imageUri, View view, FailReason failReason) { |
13 | public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { |
17 | public void onLoadingCancelled(String imageUri, View view) { |
24 | ImageSize targetSize = new ImageSize( 120 , 80 ); |
25 | imageLoader.loadImage(imageUri, targetSize, displayOptions, new SimpleImageLoadingListener() { |
27 | public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { |
ImageLoader Helpers
一些可能会用到的帮助类和方法
03 | | - clearMemoryCache() |
06 | | - denyNetworkDownloads( boolean ) |
07 | | - handleSlowNetwork( boolean ) |
12 | | - getLoadingUriForView(ImageView) |
13 | | - cancelDisplayTask(ImageView) |
15 | | - findCachedBitmapsForImageUri(...) |
16 | | - findCacheKeysForImageUri(...) |
17 | | - removeFromCache(...) |
20 | | - removeFromCache(...) |
22 | | - getCacheDirectory(Context) |
23 | | - getIndividualCacheDirectory(Context) |
24 | | - getOwnCacheDirectory(Context, String) |
Useful Info
1.使用默认值时缓存无效。如果你想要加载图片的时候使用内存/磁盘中的缓存,那么你应该这样设置DisplayImageOptions:
03 | DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() |
09 | ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) |
11 | .defaultDisplayImageOptions(defaultOptions) |
14 | ImageLoader.getInstance().init(config); |
18 | ImageLoader.getInstance().displayImage(imageUrl, imageView); |
或者这样:
1 | DisplayImageOptions options = new DisplayImageOptions.Builder() |
7 | ImageLoader.getInstance().displayImage(imageUrl, imageView, options); |
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 ; |
2 | boolean pauseOnFling = true ; |
3 | PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling); |
4 | listView.setOnScrollListener(listener); |
源博客文章链接:http://linkyan.com/2013/05/android-universal-image-loader/