Android Universal Image Loader 磁盘缓存分析

前言

图片加载方面UIL的确很好用,所有有空就看了看UIL的源码,方面自己了解原理并能更熟练的使用它。

源码版本:Android-Universal-Image-Loader-1.9.5

项目地址:Universal-Image-Loader

注意点:此版本discCache过时,用diskCache替换

磁盘缓存分析

DisplayImageOptions开启磁盘缓存

options.cacheOnDisk(true);

在ImageLoaderConfiguration的里面配置磁盘缓存空间

config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
config.diskCache(new UnlimitedDiskCache(cacheDir)); // 你可以传入自己的磁盘缓存
  • 1.磁盘缓存路径

如果使用的是自定义的缓存路径当然没啥问题,但是我觉得还是有必要知道默认缓存路径,不然我们怎么知道有没有缓存成功呢?

获取缓存目录

File file = ImageLoader.getInstance().getDiskCache().getDirectory();
String filePath = file.getAbsolutePath();

获得结果为:
/storage/emulated/0/Android/data/com.nostra13.universalimageloader/cache/uil-images
即:位于SD卡的Android/data/应用程序包名/cache/uil-images文件夹下
例如:
/Android/data/com.baidu.netdisk/cache/uil-images

将该文件夹下的文件复制出来,后缀名加上.jpg即可看到图片。

创建DiskCache的源码部分
DefaultConfigurationFactory.java

    /**
     * Creates default implementation of {@link DiskCache} depends on incoming parameters
     */
    public static DiskCache createDiskCache(Context context,
            FileNameGenerator diskCacheFileNameGenerator,
            long diskCacheSize, int diskCacheFileCount) {
        File reserveCacheDir = createReserveDiskCacheDir(context);
        if (diskCacheSize > 0 || diskCacheFileCount > 0) {
            File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context);
            try {
                return new LruDiskCache(individualCacheDir, reserveCacheDir, 
                diskCacheFileNameGenerator, diskCacheSize,diskCacheFileCount);
                //LruDiskCache 缓存满时优先删除最近最少使用的元素。
            } catch (IOException e) {
                L.e(e);
                // continue and create unlimited cache
            }
        }
        File cacheDir = StorageUtils.getCacheDirectory(context);
        return new UnlimitedDiskCache(cacheDir, reserveCacheDir, diskCacheFileNameGenerator);
    }

    /** Creates reserve disk cache folder which will be used if primary disk cache folder becomes unavailable */
    private static File createReserveDiskCacheDir(Context context) {
        File cacheDir = StorageUtils.getCacheDirectory(context, false);
        File individualDir = new File(cacheDir, "uil-images");//指定缓存目录
        if (individualDir.exists() || individualDir.mkdir()) {
            cacheDir = individualDir;
        }
        return cacheDir;
    }
  • 2.磁盘缓存时机

既然开启了磁盘缓存
即:cacheOnDisk = true;

在DisplayImageOptions.java 看看谁调用了

    public boolean isCacheOnDisk() {
        return cacheOnDisk;
    }

毫无疑问,加载图片之前需要用到
LoadAndDisplayImageTask.java

    private Bitmap tryLoadBitmap() throws TaskCancelledException {
        Bitmap bitmap = null;
        try {
            File imageFile = configuration.diskCache.get(uri);
            if (imageFile != null && imageFile.exists() && imageFile.length() > 0) {
            //有缓存当然就直接用缓存啦~
                L.d(LOG_LOAD_IMAGE_FROM_DISK_CACHE, memoryCacheKey);
                loadedFrom = LoadedFrom.DISC_CACHE;

                checkTaskNotActual();
                bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
            }
            if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
                L.d(LOG_LOAD_IMAGE_FROM_NETWORK, memoryCacheKey);
                loadedFrom = LoadedFrom.NETWORK;

                String imageUriForDecoding = uri;
                if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {
                //判断是否需要磁盘缓存,如果是调用tryCacheImageOnDisk()
                    imageFile = configuration.diskCache.get(uri);
                    if (imageFile != null) {
                        imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());
                    }
                }

                checkTaskNotActual();
                bitmap = decodeImage(imageUriForDecoding);
                //如果imageUriForDecoding是磁盘的uri就从磁盘取流,否则网络取流
                //decodeImage里面调用的是ImageDownloader.getStream()方法

                if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
                    fireFailEvent(FailType.DECODING_ERROR, null);
                }
            }
        } catch (IllegalStateException e) {
            fireFailEvent(FailType.NETWORK_DENIED, null);
        } catch (TaskCancelledException e) {
            throw e;
        } catch (IOException e) {
            L.e(e);
            fireFailEvent(FailType.IO_ERROR, e);
        } catch (OutOfMemoryError e) {
            L.e(e);
            fireFailEvent(FailType.OUT_OF_MEMORY, e);
        } catch (Throwable e) {
            L.e(e);
            fireFailEvent(FailType.UNKNOWN, e);
        }
        return bitmap;
    }

tryCacheImageOnDisk()方法

    /** @return <b>true</b> - if image was downloaded successfully; <b>false</b> - otherwise */
    private boolean tryCacheImageOnDisk() throws TaskCancelledException {
        L.d(LOG_CACHE_IMAGE_ON_DISK, memoryCacheKey);

        boolean loaded;
        try {
            loaded = downloadImage();//去下载图片
            if (loaded) {
            //下载成功
                int width = configuration.maxImageWidthForDiskCache;
                int height = configuration.maxImageHeightForDiskCache;
                if (width > 0 || height > 0) {
                    L.d(LOG_RESIZE_CACHED_IMAGE_FILE, memoryCacheKey);
                    resizeAndSaveImage(width, height); // TODO : process boolean result
                    //根据用户配置的宽高保存图片
                }
            }
        } catch (IOException e) {
            L.e(e);
            loaded = false;
        }
        return loaded;
    }

图片下载方法:downloadImage()

    private boolean downloadImage() throws IOException {
        InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
        if (is == null) {
            L.e(ERROR_NO_IMAGE_STREAM, memoryCacheKey);
            return false;
        } else {
            try {
                return configuration.diskCache.save(uri, is, this);
                //下载完毕,存进diskCache
            } finally {
                IoUtils.closeSilently(is);
            }
        }
    }

图片根据用户配置重存 resizeAndSaveImage(int maxWidth, int maxHeight)

    /** Decodes image file into Bitmap, resize it and save it back */
    private boolean resizeAndSaveImage(int maxWidth, int maxHeight) throws IOException {
        // Decode image file, compress and re-save it
        boolean saved = false;
        File targetFile = configuration.diskCache.get(uri);
        //刚刚下载完不是存进去了吗?拿出来改造~
        if (targetFile != null && targetFile.exists()) {
            ImageSize targetImageSize = new ImageSize(maxWidth, maxHeight);
            DisplayImageOptions specialOptions = new DisplayImageOptions.Builder().cloneFrom(options)
                    .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();
            ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey,
                    Scheme.FILE.wrap(targetFile.getAbsolutePath()), uri, targetImageSize, ViewScaleType.FIT_INSIDE,
                    getDownloader(), specialOptions);
            Bitmap bmp = decoder.decode(decodingInfo);
            if (bmp != null && configuration.processorForDiskCache != null) {
                L.d(LOG_PROCESS_IMAGE_BEFORE_CACHE_ON_DISK, memoryCacheKey);
                bmp = configuration.processorForDiskCache.process(bmp);
                if (bmp == null) {
                    L.e(ERROR_PROCESSOR_FOR_DISK_CACHE_NULL, memoryCacheKey);
                }
            }
            if (bmp != null) {
                saved = configuration.diskCache.save(uri, bmp);
                //ok改造完再存回去
                bmp.recycle();
            }
        }
        return saved;
    }
  • 3磁盘缓存类型

LimitedAgeDiskCache和UnlimitedDiskCache
两个都是继承了BaseDiskCache

  • LimitedAgeDiskCache限制了缓存对象最长存活周期的磁盘缓存;
  • UnlimitedDiskCache与BaseDiskCache没啥区别只是命名更让人好理解。
    DiskCache diskCache;
    if (limit > 0) {//limit表示Max file age (in seconds)
        diskCache = new LimitedAgeDiskCache(cacheDir, limit);
    } else {
        diskCache = new UnlimitedDiskCache(cacheDir);
    }
    config.diskCache(diskCache);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值