2.开源项目https://github.com/nostra13/Android-Universal-Image-Loader的使用说明
Quick Setup
1. Include library
Manual:
Put the JAR in the libs subfolder of your Android project
or
Maven dependency:
<dependency><groupId>com.nostra13.universalp_w_picpathloader</groupId><artifactId>universal-p_w_picpath-loader</artifactId><version>1.8.4</version></dependency>
2. Android Manifest
<manifest><uses-permissionandroid:name="android.permission.INTERNET"/><!-- Include next permission if you want to allow UIL to cache p_w_picpaths on SD card --><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<applicationandroid:name="MyApplication">
...
</application></manifest>
3. Application class
publicclassMyApplicationextendsApplication{@OverridepublicvoidonCreate(){super.onCreate();// Create global configuration and initialize ImageLoader with this configurationImageLoaderConfigurationconfig=newImageLoaderConfiguration.Builder(getApplicationContext())....build();ImageLoader.getInstance().init(config);}}
Configuration and Display Options
ImageLoader Configuration (
ImageLoaderConfiguration
) is global for application.Display Options (
DisplayImageOptions
) are local for every display task (ImageLoader.displayImage(...)
).
Configuration
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.FilecacheDir=StorageUtils.getCacheDirectory(context);ImageLoaderConfigurationconfig=newImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(480,800)// default = device screen dimensions.discCacheExtraOptions(480,800,CompressFormat.JPEG,75).taskExecutor(...).taskExecutorForCachedImages(...).threadPoolSize(3)// default.threadPriority(Thread.NORM_PRIORITY-1)// default.tasksProcessingOrder(QueueProcessingType.FIFO)// default.denyCacheImageMultipleSizesInMemory().memoryCache(newLruMemoryCache(2*1024*1024)).memoryCacheSize(2*1024*1024).discCache(newUnlimitedDiscCache(cacheDir))// default.discCacheSize(50*1024*1024).discCacheFileCount(100).discCacheFileNameGenerator(newHashCodeFileNameGenerator())// default.p_w_picpathDownloader(newBaseImageDownloader(context))// default.p_w_picpathDecoder(newBaseImageDecoder())// default.defaultDisplayImageOptions(DisplayImageOptions.createSimple())// default.enableLogging().build();
Display Options
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.DisplayImageOptionsoptions=newDisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).resetViewBeforeLoading().delayBeforeLoading(1000).cacheInMemory().cacheOnDisc().preProcessor(...).postProcessor(...).extraForDownloader(...).p_w_picpathScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default.bitmapConfig(Bitmap.Config.ARGB_8888)// default.decodingOptions(...).displayer(newSimpleBitmapDisplayer())// default.handler(newHandler())// default.build();
Usage
Acceptable URIs examples
Stringp_w_picpathUri="http://site.com/p_w_picpath.png";// from WebStringp_w_picpathUri="file:///mnt/sdcard/p_w_picpath.png";// from SD cardStringp_w_picpathUri="content://media/external/audio/albumart/13";// from content providerStringp_w_picpathUri="assets://p_w_picpath.png";// from assetsStringp_w_picpathUri="drawable://"+R.drawable.p_w_picpath;// from drawables (only p_w_picpaths, non-9patch)
NOTE: Use drawable://
only if you really need it! Always consider the native way to load drawables -ImageView.setImageResource(...)
instead of using of ImageLoader
.
Simple
// Load p_w_picpath, decode it to Bitmap and display Bitmap in ImageViewp_w_picpathLoader.displayImage(p_w_picpathUri,p_w_picpathView);
// Load p_w_picpath, decode it to Bitmap and return Bitmap to callbackp_w_picpathLoader.loadImage(p_w_picpathUri,newSimpleImageLoadingListener(){@OverridepublicvoidonLoadingComplete(Stringp_w_picpathUri,Viewview,BitmaploadedImage){// Do whatever you want with Bitmap}});
Complete
// Load p_w_picpath, decode it to Bitmap and display Bitmap in ImageViewp_w_picpathLoader.displayImage(p_w_picpathUri,p_w_picpathView,displayOptions,newImageLoadingListener(){@OverridepublicvoidonLoadingStarted(Stringp_w_picpathUri,Viewview){...}@OverridepublicvoidonLoadingFailed(Stringp_w_picpathUri,Viewview,FailReasonfailReason){...}@OverridepublicvoidonLoadingComplete(Stringp_w_picpathUri,Viewview,BitmaploadedImage){...}@OverridepublicvoidonLoadingCancelled(Stringp_w_picpathUri,Viewview){...}});
// Load p_w_picpath, decode it to Bitmap and return Bitmap to callbackImageSizetargetSize=newImageSize(120,80);// result Bitmap will be fit to this sizep_w_picpathLoader.loadImage(p_w_picpathUri,targetSize,displayOptions,newSimpleImageLoadingListener(){@OverridepublicvoidonLoadingComplete(Stringp_w_picpathUri,Viewview,BitmaploadedImage){// Do whatever you want with Bitmap}});
ImageLoader Helpers
Other useful methods and classes to consider.
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
Also look into more detailed Library Map
Useful Info
Caching is NOT enabled by default. If you want loaded p_w_picpaths will be cached in memory and/or on disc 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 methodDisplayImageOptionsdefaultOptions=newDisplayImageOptions.Builder()....cacheInMemory().cacheOnDisc()....build();ImageLoaderConfigurationconfig=newImageLoaderConfiguration.Builder(getApplicationContext())....defaultDisplayImageOptions(defaultOptions)....build();ImageLoader.getInstance().init(config);// Do it on Application start
// Then later, when you want to display p_w_picpathImageLoader.getInstance().displayImage(p_w_picpathUrl,p_w_picpathView);// Default options will be used
or this way:
DisplayImageOptionsoptions=newDisplayImageOptions.Builder()....cacheInMemory().cacheOnDisc()....build();ImageLoader.getInstance().displayImage(p_w_picpathUrl,p_w_picpathView,options);// Incoming options will be used
If you enabled disc caching then UIL try to cache p_w_picpaths on external storage (/sdcard/Android/data/[package_name]/cache). If external storage is not available then p_w_picpaths are cached on device's filesytem. To provide caching on external storage (SD card) add following permission to AndroidManifest.xml:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
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
andandroid:layout_height
parametersGet
android:maxWidth
and/orandroid:maxHeight
parametersGet 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 andsave memory.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.RGB_565)
in display options. Bitmaps in RGB_565 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
.p_w_picpathScaleType(ImageScaleType.IN_SAMPLE_INT)
in display options. Or try.p_w_picpathScaleType(ImageScaleType.EXACTLY)
.Avoid using RoundedBitmapDisplayer. It creates new Bitmap object with ARGB_8888 config for displaying during work.
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 < 9FIFOLimitedMemoryCache
(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)
For disc cache configuration (
ImageLoaderConfiguration.discCache(...)
) you can use already prepared implementations:UnlimitedDiscCache
(The fastest cache, doesn't limit cache size) - Used by defaultTotalSizeLimitedDiscCache
(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.
To display bitmap (
DisplayImageOptions.displayer(...)
) you can use already prepared implementations:RoundedBitmapDisplayer
(Displays bitmap with rounded corners)FadeInBitmapDisplayer
(Displays p_w_picpath with "fade in" animation)
To avoid list (grid, ...) scrolling lags you can use
PauseOnScrollListener
:booleanpauseOnScroll=false;// or truebooleanpauseOnFling=true;// or falsePauseOnScrollListenerlistener=newPauseOnScrollListener(p_w_picpathLoader,pauseOnScroll,pauseOnFling);listView.setOnScrollListener(listener);
1.AysncTaska使用系统的线程池,默认核心线程5个,最大等待执行的线程数是10个,如果需要定制,可以执行如下代码
UpdateTask task=new UpdateTask();
task.executeOnExecutor(threadPool,"XXXXXXXXXXXXXXXXXXXX");
2.如果使用线程池
ThreadPoolExecutor threadPool=new ThreadPoolExecutor(
3,10,1,TimeUnit.SECONDS,new ArrayBlockingQueue<Bunnable>(5),new ThreadPoolExceutor.CallerRunsPolicy());
threadPool.execute(new Runable()
{
public void run(){}
}
);
AsyncTask
适用于网络访问请求数据
Handler
适用在大量的UI需要更新的
Thread
Message
ThreadPool
转载于:https://blog.51cto.com/4789781/1219423