當前位置:首頁 » 編程語言 » lrujava

lrujava

發布時間: 2024-12-10 08:26:33

『壹』 android disklrucache怎麼使用

下面是一個簡單的DiskLruCache實現。然而推薦的實現DiskLruCache方案請參考Android4.0中(libcore/luni/src/main/java/libcore/io/DiskLruCache.java)源碼。本文使用的是之前版本中的簡單實現(Quick Search中是另外的實現).

顯示是簡單實現DiskLruCache更新後的例子:

private DiskLruCache mDiskCache;
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
private static final String DISK_CACHE_SUBDIR = "thumbnails";

@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Initialize memory cache
...
File cacheDir = getCacheDir(this, DISK_CACHE_SUBDIR);
mDiskCache = DiskLruCache.openCache(this, cacheDir, DISK_CACHE_SIZE);
...
}

class BitmapWorkerTask extends AsyncTask {
...
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
final String imageKey = String.valueOf(params[0]);

// Check disk cache in background thread
Bitmap bitmap = getBitmapFromDiskCache(imageKey);

if (bitmap == null) { // Not found in disk cache
// Process as normal
final Bitmap bitmap = (
getResources(), params[0], 100, 100));
}

// Add final bitmap to caches
addBitmapToCache(String.valueOf(imageKey, bitmap);

return bitmap;
}
...
}

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
if (!mDiskCache.containsKey(key)) {
mDiskCache.put(key, bitmap);
}
}

public Bitmap getBitmapFromDiskCache(String key) {
return mDiskCache.get(key);
}

// 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 getCacheDir(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.getExternalStorageState() == Environment.MEDIA_MOUNTED
|| !Environment.isExternalStorageRemovable() ?
context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();

return new File(cachePath + File.separator + uniqueName);
}
內存緩存檢查在UI線程中做,磁碟緩存的檢查在後台線程中。硬碟操作不應在UI線程中。圖片處理完成後應將其加入正在使用的內存、磁碟緩存中。

熱點內容
伺服器如何添加聯想de存儲 發布:2025-10-16 09:30:39 瀏覽:927
站群伺服器ip怎麼解析 發布:2025-10-16 09:25:06 瀏覽:473
編程打古詩 發布:2025-10-16 09:17:51 瀏覽:643
python正態隨機數 發布:2025-10-16 09:13:27 瀏覽:211
新建域用戶如何保存原來的配置 發布:2025-10-16 09:05:01 瀏覽:967
安卓相機怎麼調出蘋果相機的效果 發布:2025-10-16 08:56:21 瀏覽:693
我的世界大伺服器列表 發布:2025-10-16 08:50:09 瀏覽:445
如何找回發票軟體用戶名密碼 發布:2025-10-16 08:35:54 瀏覽:305
電腦怎麼打開伺服器界面 發布:2025-10-16 08:13:40 瀏覽:408
115安卓同時下載的文件在哪裡 發布:2025-10-16 08:05:34 瀏覽:413