Android ImageLoader

Universal_Image_Loader源码解析

2017-03-11  本文已影响64人  地球是猿的

UIL是一个老牌的开源图片加载框架,前几年做Android开发的小伙伴肯定都非常熟悉。虽然现在UIL的作者已经停止进行代码维护,而且后面又有很多优秀的开源图片加载框架推出,比如Glide、Picasso、Fresco等。但是这并不妨碍我们对于UIL的基本使用。今天就带着大家一起来从源码的角度来认识一下Universal_Image_Loader。

一、初识UIL

UIL的基本特性,这里简单罗列一下:

  1. 多线程下载图片,图片可以来源于网络,文件系统,项目文件夹assets中以及drawable中等
  2. 支持随意的配置ImageLoader,例如线程池,图片下载器,内存缓存策略,硬盘缓存策略,图片显示选项以及其他的一些配置
  3. 支持图片的内存缓存,文件系统缓存或者SD卡缓存
  4. 支持图片下载过程的监听
  5. 根据控件(ImageView)的大小对Bitmap进行裁剪,减少Bitmap占用过多的内存
  6. 较好的控制图片的加载过程,例如暂停图片加载,重新开始加载图片,一般使用在ListView,GridView中,滑动过程中暂停加载图片,停止滑动的时候去加载图片
  7. 提供在较慢的网络下对图片进行加载

基本使用方法:

  1. 在Gradle的dependency下加入
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
  2. 加入权限:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" />
  3. 在全局Application中new一个ImageLoder对象,这个对象是单例模式的:
        public class MyApplication extends Application {  
           
             @Override  
             public void onCreate() {  
                 super.onCreate();  
           
                 //创建默认的ImageLoader配置参数  
                ImageLoaderConfiguration configuration = ImageLoaderConfiguration  
                         .createDefault(this);  
                   
                 //进行初始化操作
                 ImageLoader.getInstance().init(configuration);  
             }  
           
         }  

注意:

  1. 只能配置一次,如多次配置,则默认第一次的配置参数。
  2. 这里主要是imageloader的配置参数是个重点。
    一般用默认配置就ok。但也提供了一些特定的设置,只有真的需要的时候才用。
  3. 下面是全部配置,如果需要单独设定某个值得时候可以使用。
    具体意思,根据方法名自己理解,或者百度。这里不再一一讲解.
        File cacheDir = StorageUtils.getCacheDirectory(context);  //缓存文件夹路径
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                        .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽
                        .diskCacheExtraOptions(480, 800, null)  // 本地缓存的详细信息(缓存的最大长宽),最好不要设置这个 
                        .taskExecutor(...)
                        .taskExecutorForCachedImages(...)
                        .threadPoolSize(3) // default  线程池内加载的数量
                        .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                        .denyCacheImageMultipleSizesInMemory()
                        .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
                        .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                        .memoryCacheSizePercentage(13) // default
                        .diskCache(new UnlimitedDiscCache(cacheDir)) // default 可以自定义缓存路径  
                        .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
                        .diskCacheFileCount(100)  // 可以缓存的文件数量 
                        // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密
                        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) 
                        .imageDownloader(new BaseImageDownloader(context)) // default
                        .imageDecoder(new BaseImageDecoder()) // default
                        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                        .writeDebugLogs() // 打印debug log
                .build(); //开始构建
  1. 配置加载图片的属性,这里主要是一些加载失败的默认图片,加载过程中的图片,缓存位置,bitmap属性等。这里,我在使用的时候定义了三个DisplayImageOptions对象,分别是加载大图、中图、小图。基本涵盖了app中图片的使用。下面给出一个小图的options
DisplayImageOptions smallImageOptions  = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.default_pic_small)
            .showImageOnFail(R.drawable.default_pic_small)
            .showImageForEmptyUri(R.drawable.default_pic_small)
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
  1. 开始加载图片
ImageLoader.getInstance().displayImage(url, imageView, option);
String drawableUrl = Scheme.DRAWABLE.wrap("R.drawable.image"); 
ImageLoader.getInstance().displayImage(drawableUrl , imageView, option);
或者 
ImageLoader.getInstance().displayImage("drawable://" + imageId,
                imageView);
String imageUrl = ImageDownloader.Scheme.FILE.wrap("/mnt/sdcard/image.png");
ImageLoader.getInstance().displayImage(imageUrl, imageView, option);
String assetsUrl = Scheme.ASSETS.wrap("image.png");  
ImageLoader.getInstance().displayImage(assetsUrl , imageView, option);
String contentprividerUrl = "content://media/external/audio/albumart/13";  
ImageLoader.getInstance().displayImage(contentprividerUrl , imageView, option);
  1. GirdView,ListView加载图片
    当我们快速滑动GridView,ListView,我们希望能停止图片的加载,而在GridView,ListView停止滑动的时候加载当前界面的图片。我们只需要在初始化ListView和GridView的时候,加上下面两行配置:
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  
gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  

二、UID的图片缓存策略

  1. 图片缓存的概念,简单点来说当你第一次打开某个界面的时候,图片可能要等待几秒钟才能加载完成,但当你第二次进入时,图片直接就可以显示出来,相对于第一次加载快了很多。这里运用的就是图片缓存技术。
  2. 三级缓存。一般的策略是先从内存中找,没有的话再去本地disk中找,再没有的话就从网络获取。下面的文章主要说一下内存缓存和磁盘缓存,网络缓存就是重新加载了。三级缓存的特点:

三、内存缓存

  1. 内存缓存中的强引用和弱引用
  1. UIL中的内存缓存策略
    UIL提供的内存缓存策略有下面几种,大家可以自己去看下源码,非常简单。
    (1)使用的是强引用缓存
    • LruMemoryCache(这个类就是这个开源框架默认的内存缓存类,缓存的是bitmap的强引用,下面我会从源码上面分析这个类)

(2) 使用强引用和弱引用相结合的缓存有
- UsingFreqLimitedMemoryCache(如果缓存的图片总量超过限定值,先删除使用频率最小的bitmap)
- LRULimitedMemoryCache(这个也是使用的lru算法,和LruMemoryCache不同的是,他缓存的是bitmap的弱引用)
- FIFOLimitedMemoryCache(先进先出的缓存策略,当超过设定值,先删除最先加入缓存的bitmap)
- LargestLimitedMemoryCache(当超过缓存限定值,先删除最大的bitmap对象)
- LimitedAgeMemoryCache(当 bitmap加入缓存中的时间超过我们设定的值,将其删除)

(3) 只使用弱引用缓存
- WeakMemoryCache(这个类缓存bitmap的总大小没有限制,唯一不足的地方就是不稳定,缓存的图片容易被回收掉)

  1. UIL手动修改内存缓存策略
    在Application中初始化ImageLoaderConfiguration的时候,加上memoryCache就可以了。
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)  
        .memoryCache(new WeakMemoryCache())  
        .build();  
  1. LruMemoryCache 类解析
    这里已LruMemoryCache 类为例进行分析,源码的话,就不贴了。只列出关键的代码。
    private final LinkedHashMap<String, Bitmap> map;  
    private final int maxSize;  
    /** Size of this cache in bytes */  
    private int size;  

LruMemoryCache 缓存了一个LinkedHashMap<String, Bitmap> map对象,用来保存图片。同时还定义了一个最大缓存值,以及一个当前的缓存值。

 /** 
     * Remove the eldest entries until the total of remaining entries is at or below the requested size. 
     * 
     * @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements. 
     */  
    private void trimToSize(int maxSize) {  
        while (true) {  
            String key;  
            Bitmap value;  
            synchronized (this) {  
                if (size < 0 || (map.isEmpty() && size != 0)) {  
                    throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!");  
                }  
  
                if (size <= maxSize || map.isEmpty()) {  
                    break;  
                }  
  
                Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();  
                if (toEvict == null) {  
                    break;  
                }  
                key = toEvict.getKey();  
                value = toEvict.getValue();  
                map.remove(key);  
                size -= sizeOf(key, value);  
            }  
        }  
    } 

如果当前缓存的bitmap总数小于设定值maxSize,不做任何处理,如果当前缓存的bitmap总数大于maxSize,删除LinkedHashMap中的第一个元素,size中减去该bitmap对应的byte数

四、硬盘缓存

  1. UIL提供的硬盘缓存策略

五、UIL加载一张网络图片的过程

  1. 先看下我们平常使用加载图片的代码:
    ImageLoader.getInstance().displayImage(imageUrl, imageView, options);
  2. 再看下displayImage的源码:
    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
        displayImage(uri, new ImageViewAware(imageView), options, null, null);
    }

这个ImageViewAware是什么?看下源码的注释:
"Wrapper for Android {@link android.widget.ImageView ImageView}. Keeps weak reference of ImageView to prevent memory leaks."
将ImageView的强引用变成弱引用,当内存不足的时候,可以更好的回收ImageView对象,还有就是获取ImageView的宽度和高度。使得我们可以根据ImageView的宽高去对图片进行一个裁剪,减少内存的使用。

看下ImageLoader中的displayImage方法,上代码:

/**
     * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />
     * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
     *
     * @param uri              Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
     * @param imageAware       {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}
     *                         which should display image
     * @param options          {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image
     *                         decoding and displaying. If <b>null</b> - default display image options
     *                         {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)
     *                         from configuration} will be used.
     * @param listener         {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires
     *                         events on UI thread if this method is called on UI thread.
     * @param progressListener {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener
     *                         Listener} for image loading progress. Listener fires events on UI thread if this method
     *                         is called on UI thread. Caching on disk should be enabled in
     *                         {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions options} to make
     *                         this listener work.
     * @throws IllegalStateException    if {@link #init(ImageLoaderConfiguration)} method wasn't called before
     * @throws IllegalArgumentException if passed <b>imageAware</b> is null
     */
    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,
            ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        checkConfiguration();
        if (imageAware == null) {
            throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
        }
        if (listener == null) {
            listener = emptyListener;
        }
        if (options == null) {
            options = configuration.defaultDisplayImageOptions;
        }

        if (TextUtils.isEmpty(uri)) {
            engine.cancelDisplayTaskFor(imageAware);
            listener.onLoadingStarted(uri, imageAware.getWrappedView());
            if (options.shouldShowImageForEmptyUri()) {
                imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));
            } else {
                imageAware.setImageDrawable(null);
            }
            listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);
            return;
        }

        ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());
        String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
        engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);

        listener.onLoadingStarted(uri, imageAware.getWrappedView());

        Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);
        if (bmp != null && !bmp.isRecycled()) {
            L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);

            if (options.shouldPostProcess()) {
                ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,
                        options, listener, progressListener, engine.getLockForUri(uri));
                ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo,
                        defineHandler(options));
                if (options.isSyncLoading()) {
                    displayTask.run();
                } else {
                    engine.submit(displayTask);
                }
            } else {
                options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);
                listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);
            }
        } else {
            if (options.shouldShowImageOnLoading()) {
                imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));
            } else if (options.isResetViewBeforeLoading()) {
                imageAware.setImageDrawable(null);
            }

            ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,
                    options, listener, progressListener, engine.getLockForUri(uri));
            LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo,
                    defineHandler(options));
            if (options.isSyncLoading()) {
                displayTask.run();
            } else {
                engine.submit(displayTask);
            }
        }
    }

我大致说下处理流程:

  1. 检查配置是否初始化;
  2. 检查imageAware,也就是ImageView是否为空;
  3. 检查ImageLoadingListener和ImageLoadingProgressListener是否为空,如果为空就使用默认的配置。
  4. 判断图片地址。如果为空就显示配置的空图片,并取消网络任务,同时调用ImageLoadingListener的onLoadingComplete方法,结束本次加载。如果图片地址不为空,那么进行下面的步骤
  5. 将ImageView的宽高封装成ImageSize对象.如果获取ImageView的宽高为0,就会使用手机屏幕的宽高作为ImageView的宽高。
  6. 从内存中查找这个图片。如果从内存中找到了,那么再判断显示图片的options.shouldPostProcess()是否为true。postProcessor这个属性主要是判断是否需要对取到的这个图片进行处理,比如切成圆角边等。这个对应的需要自己实现BitmapProcessor接口来处理这个bitmap。如果需要处理图片,就进行处理,然后显示。如果不需要处理,就直接显示到imageAware上去。加载完成。
  7. 如果没有从内存中找到这张图片,那么就实例化一个LoadAndDisplayImageTask对象。这个对象实现了Runnable,如果配置了isSyncLoading为true, 直接执行LoadAndDisplayImageTask的run方法,表示同步,默认是false,将LoadAndDisplayImageTask提交给线程池对象。这个对象的主要作用是去disk或者网络中去加载图片。

下面看下LoadAndDisplayImageTask是如何从disk或者网络加载图片的。先看它的run方法

    @Override
    public void run() {
        if (waitIfPaused()) return;
        if (delayIfNeed()) return;

        ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
        L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
        if (loadFromUriLock.isLocked()) {
            L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
        }

        loadFromUriLock.lock();
        Bitmap bmp;
        try {
            checkTaskNotActual();

            bmp = configuration.memoryCache.get(memoryCacheKey);
            if (bmp == null || bmp.isRecycled()) {
                bmp = tryLoadBitmap();
                if (bmp == null) return; // listener callback already was fired

                checkTaskNotActual();
                checkTaskInterrupted();

                if (options.shouldPreProcess()) {
                    L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);
                    bmp = options.getPreProcessor().process(bmp);
                    if (bmp == null) {
                        L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
                    }
                }

                if (bmp != null && options.isCacheInMemory()) {
                    L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
                    configuration.memoryCache.put(memoryCacheKey, bmp);
                }
            } else {
                loadedFrom = LoadedFrom.MEMORY_CACHE;
                L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
            }

            if (bmp != null && options.shouldPostProcess()) {
                L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey);
                bmp = options.getPostProcessor().process(bmp);
                if (bmp == null) {
                    L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
                }
            }
            checkTaskNotActual();
            checkTaskInterrupted();
        } catch (TaskCancelledException e) {
            fireCancelEvent();
            return;
        } finally {
            loadFromUriLock.unlock();
        }

        DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
        runTask(displayBitmapTask, syncLoading, handler, engine);
    }
  1. if (waitIfPaused()) return;这句话主要是用在ListView或者GridView在滑动过程中,不去加载图片。这里需要配合
    ListView.setOnScrollListener(new PauseOnScrollListener(pauseOnScroll, pauseOnFling ))
  2. if (waitIfPaused()) return;和if (delayIfNeed()) return;的返回值最终都由一个方法isTaskNotActual决定。看下这个方法的源码
private boolean isTaskNotActual() {
        return isViewCollected() || isViewReused();
    }

isViewCollected()是判断我们ImageView是否被垃圾回收器回收了,如果回收了,LoadAndDisplayImageTask方法的run()就直接返回了,isViewReused()判断该ImageView是否被重用,被重用run()方法也直接返回。被重用的情况主要发生在ListView和GridView当中,如果当前加载的ImageView已经被重用了,那么就没必要继续加载之前的图片了,所以直接返回。

  1. 检查完可以去加载图片了。先加一个锁ReentrantLock。这个锁的作用就是相同url的请求只执行一次。比如listview中的一个item需要从网上加载图片。我们用手机滑动ListView让这个item,一会滑入界面,然后滑出后再马上滑入。重复几次的话,就会有很多个相同url的请求。加了这个锁的作用,这些请求只执行一遍,而不是全部去执行一遍。
    再看下用了这个url请求后干了什么
  2. checkTaskNotActual()。这个也是检查view是否被回收和复用。
  3. 再从缓存中检查一遍,如果缓存中没有,那么去tryLoadBitmap();这个就是加载的方法。大概的流程就是先从disk缓存中获取图片,如果没有再去从网络中获取,然后将bitmap保存在文件系统中。
  4. 从服务器上获取图片保存到本地是调用了tryCacheImageOnDisk这个方法。这个方法里调用了downloadImage这个方法去下载图片。
  5. 剩下的就是显示图片了。 同样会检查一遍view有没有被回收,被复用。

至此,显示图片的过程就结束了。

笔者在写这篇博客的过程中,从以下两篇文章中学到了很多有价值的东西,十分感谢!
Android 开源框架Universal-Image-Loader完全解析
Android开源框架Universal-Image-Loader详解

上一篇 下一篇

猜你喜欢

热点阅读