ImageLoader总结

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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值