from : http://blog.csdn.net/yuanlongquan753/article/details/52709658?ref=myread
UniversalImageLoader
问题:
从网络获取图片、显示、回收,每个环节都可能造成应用的OOM(如果没做相关的处理的话)。像ListView或者是GridView中,一页就含有大量的图片,快速滑动的时候,没有OOM也会有卡顿的现象。
解决办法:
使用异步加载网络图片、缓存以及显示。
ImageLoader的工作原理:
最后下载好图片,同时缓存到内存和本地中。 当退出一个页面的时候,内存中ImageLoader的缓存将会全部清除,节省大量内存。 ImageLoader对图片的引用形式为软引用,当内不足的时候,将会被GC。
UniversalImageLoader的三大组件
ImageLoadConfiguration: 对图片缓存过程进行总体的配置,包括内存缓存大小、本地缓存大小以及缓存的位置,下载策略(FIFO,LIFO) DisplayImageOptions: 控制图片显示的细节,比如指定下载中、下载失败、URL为空等默认图片,是否将图片缓存到内存或者硬盘中。 ImageLoader: 在显示图片的地方,比如RecyclerView的Adapter中,使用displayImage把Url对应的图片显示在ImageView上。
使用流程:
1. 添加库的三种方法
a. 将jar 包添加到lib目录下面
b.Maven dependency:
< dependency > < groupId > com.nostra13.universalimageloader </ groupId > < artifactId > universal-image-loader </ artifactId > < version > 1.9.5 </ version > </ dependency >
c.
Gradle dependency:
< span style = "font-family:-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;font-size:14px;color:#333333;" > compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' </ span >
2、在Manifest文件中配置相关
< manifest > < uses-permission android:name = "android.permission.INTERNET" /> < uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" /> ... </ manifest >
3、 在继承Application的类中或者是在Activity中初始化配置
public class YuZhenApplication extends Application { @Override public void onCreate() { super .onCreate(); DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(R.mipmap.ic_launcher) .showImageForEmptyUri(R.mipmap.ic_launcher) .showImageOnFail(R.mipmap.ic_launcher) .bitmapConfig(Bitmap.Config.ARGB_8888) .cacheInMemory(true ) .cacheOnDisk(true ) .delayBeforeLoading(0 ) .build(); ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPriority(Thread.NORM_PRIORITY - 2 ) .memoryCacheExtraOptions(480 , 480 ) .denyCacheImageMultipleSizesInMemory() .tasksProcessingOrder(QueueProcessingType.FIFO) .memoryCache(new WeakMemoryCache()) .diskCacheFileNameGenerator(new Md5FileNameGenerator()) .defaultDisplayImageOptions(displayImageOptions) .build(); ImageLoader.getInstance().init(imageLoaderConfiguration); } }
4. Android Manifest 中添加application
< application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:supportsRtl = "true" android:name = ".SkApplication" android:theme = "@style/AppTheme" > < activity android:name = ".MainActivity" android:screenOrientation = "portrait" > < intent-filter > < action android:name = "android.intent.action.MAIN" /> < category android:name = "android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > </ application >
5. 显示图片的方法
ImageLoader.getInstance().displayImage(imageUrl,imageView);
延伸:
优化UniversalImageLoader : http://www.open-open.com/lib/view/open1433940304473.html