Android内存优化之磁盘缓存

前言:

在上一篇文章中介绍了内存缓存,内存缓存的优点就是很快,但是它又有缺点:

  • 空间小,内存缓存不可能很大;
  • 内存紧张时可能被清除;
  • 在应用退出时就会消失,做不到离线;

基于以上的缺点有时候又需要另外一种缓存,那就是磁盘缓存。大家应该都用过新闻客户端,很多都有离线功能,功能的实现就是磁盘缓存。

DiskLruCache:

在Android中用到的磁盘缓存大多都是基于DiskLruCache实现的,具体怎么使用呢?
1.创建一个磁盘缓存对象:
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize);

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

2.获取缓存路径:

1
2
3
4
5
6
7
8
9
10
11
12
// Creates a unique subdirectory of the designated app cache directory. Tries to use external
// but if not mounted, falls back on internal storage.
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);
}

3.获取软件版本号:

1
2
3
4
5
6
7
8
9
public int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}

4.完整的代码如下:

1
2
3
4
5
6
7
8
9
10
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();
}

5.具体怎么使用上面创建的磁盘缓存如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//添加缓存
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;
}

总结

以上是磁盘缓存的创建和使用方法。在实际操作中内存缓存和磁盘缓存是配合起来使用的,一般先从内存缓存中读取数据,如果没有再从磁盘缓存中读取。个人水平有限,有什么问题可以留言,最好是添加我的公众号: coder_online ,我能及时的看到你的留言并给你答复。