且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android -- DiskLruCache

更新时间:2022-09-08 10:56:00


DiskLruCache

  • 创建一个磁盘缓存对象:
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)

open()方法接收四个参数,第一个参数是数据的缓存文件地址,第二个参数是当前应用程序的版本号,第三个参数是同一个key可以对应多少个缓存文件,一般都是传1,第四个参数是最多可以缓存多少字节的数据。

//创建磁盘缓存文件,首选sdcard,如果sdcard没有挂载或者没有sdcard则获取应用默认的cache目录
public static File getDiskCacheDir(Context context, String uniqueName) {
    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
                            context.getCacheDir().getPath();
 
    return new File(cachePath + File.separator + uniqueName);
}
  • 获取软件版本号
public int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }
Java

DiskLruCache mDiskLruCache = null;
try {
    File cacheDir = getDiskCacheDir(context, "thumbnails");
    if (!cacheDir.exists()) {
        cacheDir.mkdirs();
    }
    mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
} catch (IOException e) {
    e.printStackTrace();
}
  • 磁盘缓存
//添加缓存
public void addBitmapToCache(String key, Bitmap bitmap) {
    // Add to memory cache as before,把缓存放到内存缓存中
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
 
    // Also add to disk cache,把缓存放入磁盘缓存
    synchronized (mDiskCacheLock) {
        if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
            mDiskLruCache.put(key, bitmap);
        }
    }
}
//获取缓存
public Bitmap getBitmapFromDiskCache(String key) {
    synchronized (mDiskCacheLock) {
        // Wait while disk cache is started from background thread
        while (mDiskCacheStarting) {
            try {
                mDiskCacheLock.wait();
            } catch (InterruptedException e) {}
        }
        if (mDiskLruCache != null) {
            return mDiskLruCache.get(key);
        }
    }
    return null;
}

总结

以上是磁盘缓存的创建和使用方法。在实际操作中内存缓存和磁盘缓存是配合起来使用的,一般先从内存缓存中读取数据,如果没有再从磁盘缓存中读取。




本文转自我爱物联网博客园博客,原文链接:http://www.cnblogs.com/yydcdut/p/4660669.html,如需转载请自行联系原作者