Android內存優化之磁盤緩存

jopen 10年前發布 | 26K 次閱讀 Android 移動開發 Android開發

Android內存優化之磁盤緩存

前言:

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

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

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

DiskLruCache:

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

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

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

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

  • 獲取緩存路徑:

Java

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

 

  • 獲取軟件版本號:

Java

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

 

  • 具體怎么使用上面創建的磁盤緩存如下:

Java

//添加緩存
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 ,我能及時的看到你的留言并給你答復。

原文:已失效 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!