歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android內存優化之磁盤緩存

Android內存優化之磁盤緩存

日期:2017/3/1 9:27:59   编辑:Linux編程

前言:

在上一篇文章中介紹了Android內存優化之內存緩存,內存緩存的優點就是很快,但是它又有缺點:

  • 空間小,內存緩存不可能很大;
  • 內存緊張時可能被清除;
  • 在應用退出時就會消失,做不到離線;

基於以上的缺點有時候又需要另外一種緩存,那就是磁盤緩存。大家應該都用過新聞客戶端,很多都有離線功能,功能的實現就是磁盤緩存。

DiskLruCache:

在Android中用到的磁盤緩存大多都是基於DiskLruCache實現的,具體怎麼使用呢?

創建一個磁盤緩存對象:

public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize);

open()方法接收四個參數,第一個參數是數據的緩存文件地址,第二個參數是當前應用程序的版本號,第三個參數是同一個key可以對應多少個緩存文件,一般都是傳1,第四個參數是最多可以緩存多少字節的數據,10M?

獲取緩存路徑:

// Creates a unique subdirectory of the designated app cache directory. Tries to use external
// but if not mounted, falls back on internal storage.
//創建磁盤緩存文件,首選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;
}

完整的代碼如下:

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;
}

總結:以上是磁盤緩存的創建和使用方法。在實際操作中內存緩存和磁盤緩存是配合起來使用的,一般先從內存緩存中讀取數據,如果沒有再從磁盤緩存中讀取。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved