ImageLoader
ImageLoader目的是为了实现异步的网络图片加载、缓存及显示,支持多线程异步加载。特点是使用简单,效率凑合。
原理
在显示图片的时候,它会在内存中查找;如果没有,就去本地查找;如果还没有,就开一个新的线程去下载这张图片,下载成功后会把图片同时缓存在内存和本地。
github地址:https://github.com/nostra13/Android-Universal-Image-Loader
使用
1.ImageLoaderConfiguration
//在自定义的MyApplication中总体配置ImageLoader
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration config =
new ImageLoaderConfiguration.Builder(
getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheExtraOptions(480, 480)
.memoryCacheSize(2 * 1024 * 1024)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.memoryCache(new WeakMemoryCache()).build();
ImageLoader.getInstance().init(config);
}
}
2.ImageLoader
//在使用ImageView加载图片的地方,配置当前页面的ImageLoader选项。
public class PersonAdapter extends BaseAdapter {
private final ArrayList<Person> personList;
private final AppBaseActivity context;
private DisplayImageOptions options;
public PersonAdapter(ArrayList<Person> personList,
AppBaseActivity context) {
this.personList= personList;
this.context = context;
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.cacheInMemory()
.cacheOnDisc()
.build();
}
......
3. DisplayImageOptions
//在使用ImageView加载图片的地方,使用ImageLoader
Person person = personList.get(position);
holder.tvUserName.setText(person.getUserName());
holder.tvCityName.setText(person.getCityName());
context.imageLoader.displayImage(personList.get(position)
.getUserPhotoUrl(), holder.imgPhoto);
优化
图片一直会缓存在内存中,会导致内存占用过高。虽然这个是软引用,内存不够的时候会GC,但是还是应该要减少GC的次数,因此在页面销毁时,清除缓存。
protected void onDestroy() {
//回收该页面缓存在内存的图片
imageLoader.clearMemoryCache();
super.onDestroy();
}