Android內存優化之磁盤緩存
前言:
在上一篇文章中介紹了內存緩存,內存緩存的優點就是很快,但是它又有缺點:
- 空間小,內存緩存不可能很大;
- 內存緊張時可能被清除;
- 在應用退出時就會消失,做不到離線; </ul>
- 創建一個磁盤緩存對象: </ul>
- 獲取緩存路徑: </ul>
- 獲取軟件版本號: </ul>
- 完整的代碼如下: </ul>
- 具體怎么使用上面創建的磁盤緩存如下: </ul>
基于以上的缺點有時候又需要另外一種緩存,那就是磁盤緩存。大家應該都用過新聞客戶端,很多都有離線功能,功能的實現就是磁盤緩存。
DiskLruCache:
在Android中用到的磁盤緩存大多都是基于DiskLruCache實現的,具體怎么使用呢?
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize);
open()方法接收四個參數,第一個參數指定的是數據的緩存地址,第二個參數指定當前應用程序的版本號,第三個參數指定同一個key可以對應多少個緩存文件,基本都是傳1,第四個參數指定最多可以緩存多少字節的數據。
Java
</div>// 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);
}</pre>
Java
</div>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
</div>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
</div>//添加緩存 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; }</pre>
總結:以上是磁盤緩存的創建和使用方法。在實際操作中內存緩存和磁盤緩存是配合起來使用的,一般先從內存緩存中讀取數據,如果沒有再從磁盤緩存中讀取。個人水平有限,有什么問題可以留言,最好是添加我的公眾號: coder_online ,我能及時的看到你的留言并給你答復。
原文 http://www.coderonline.net/【android內存優化】android內存優化之磁盤緩