美文网首页
图片加载功能封装----基于UIL库的封装

图片加载功能封装----基于UIL库的封装

作者: JerryloveEmily | 来源:发表于2017-07-02 15:48 被阅读88次

相信做过一两年android开发的程序员,应该都使用过UIL库(Universal-Image-Loader),这是一个强大的图片加载库,支持各种配置,但是这些常用配置往往对于不用的项目,也几乎大同小异,本着代码复用,高效开发业务代码的原则,本文就来基于UIL库,做一个简单的封装。


  • 首先新建一个Android Library的module,便于多个项目共享,然后在这个module的build.gradle中加入对UIL库的依赖:
dependencies {
    ...
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
}

当然重要的两个权限也别忘记了:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 然后新建一个类ImageLoaderManager
/**
 * @author Jerry
 * 图片加载管理,基于UIL库
 */
public class ImageLoaderManager {
    // 同时最大的图片线程加载数
    public static final int THEAD_COUNT = 5;
    // 图片加载优先级
    public static final int PRIORITY = 5;
    // 磁盘缓存大小,50M
    public static final int DISK_CACHE_SIZE = 50 * 1024 * 1024;
    // 图片加载连接超时
    public static final int CONNECT_TIME_OUT = 5 * 1000;
    // 图片加载IO读取超时
    public static final int READ_TIME_OUT = 5 * 1000;

    private static ImageLoader sImageLoader = null;
    private static ImageLoaderManager sInstance = null;

    /**
     * double check,单例
     * @return 实例对象
     */
    public static ImageLoaderManager getInstance(Context context) {
        if (sInstance == null){
            synchronized (ImageLoaderManager.class){
                if (sInstance == null){
                    sInstance = new ImageLoaderManager(context.getApplicationContext());
                }
            }
        }
        return sInstance;
    }

    private ImageLoaderManager(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPoolSize(THEAD_COUNT)    // 加载图片线程池中最大的线程数
                .threadPriority(Thread.NORM_PRIORITY - PRIORITY) // 针对不同安卓系统的线程优先级的适配,加载图片的线程优先级
                .denyCacheImageMultipleSizesInMemory()  // 防止加载器缓存多套不同的尺寸到内存中
                .memoryCache(new WeakMemoryCache()) // 使用弱引用,在系统内存不足时回收图片资源
                .diskCacheSize(DISK_CACHE_SIZE) // 磁盘缓存大小
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // 使用md5来命名缓存的磁盘图片文件
                .tasksProcessingOrder(QueueProcessingType.LIFO) // 图片加载下载的顺序,后进先出算法
                .defaultDisplayImageOptions(getDefaultDisplayOptions()) // 默认的图片显示配置器
                .imageDownloader(new BaseImageDownloader(context,
                        CONNECT_TIME_OUT, READ_TIME_OUT))   // 设置图片下载器
                .writeDebugLogs()   // debug模式下打印出日志
                .build();
        sImageLoader = ImageLoader.getInstance();
        sImageLoader.init(config);
    }

    private DisplayImageOptions getDefaultDisplayOptions() {
        return new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.jsdk_img_error)    // 图片加载地址为空的时候显示的图片
                .showImageOnFail(R.drawable.jsdk_img_error)         // 图片加载失败的时候显示的图片
                .cacheInMemory(true)                                // 设置图片可以缓存到内存
                .cacheOnDisk(true)                                  // 设置图片可以缓存到磁盘
                .bitmapConfig(Bitmap.Config.ARGB_4444)              // 设置图片显示的渲染色彩的质量,减小图片占用内存
                .decodingOptions(new BitmapFactory.Options())       // 使用系统默认的解码配置
                .build();
    }

    public void showImage(ImageView imageView, String url){
        showImage(imageView, url, null);
    }

    public void showImage(ImageView imageView, String url, ImageLoadingListener loadingListener){
        showImage(imageView, url, null, loadingListener);
    }

    /**
     * 加载显示图片
     * @param imageView         图片控件
     * @param url               图片地址
     * @param opts              显示配置
     * @param listener          加载监听回调
     */
    public void showImage(ImageView imageView, String url, DisplayImageOptions opts,
                          ImageLoadingListener listener){
        if (sImageLoader != null) {
            sImageLoader.displayImage(url, imageView, opts, listener);
        }
    }
}

源码的注释写的很清楚,至于为什么这么配置图片加载器对象和显示对象,这是根据项目中使用的经营总结的。
使用也很简单,当然也可以自定义自己的加载器配置和图形显示配置,同时也可以监听图形加载情况:

ImageLoaderManager.getInstance(Activity.实例对象)
          .showImage(ivHeaderImage, "http://www.jkfds.com/jrweosdfjk.jpg")

一个简单的封装,UIL库源码还是值得多分析的,里面有很多设计思想,最简单的比如图片加载器对象的DCL,双检查单例(这边在有些情况下IPC多进程的应用场景需要注意下,单例失效的问题)图片加载器配置和图片显示配置,对于这样需要设置很多配置信息内容属性的,可以用构建者模式,灵活优雅。还可以学习到图片加载的三级缓存机制,以及图片任务下载多线程线程池任务队列的处理等等。

相关文章

网友评论

      本文标题:图片加载功能封装----基于UIL库的封装

      本文链接:https://www.haomeiwen.com/subject/emnncxtx.html