当前位置:首页 » 编程语言 » 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线程中。图片处理完成后应将其加入正在使用的内存、磁盘缓存中。

热点内容
全国各地区dns服务器地址大全 发布:2025-10-16 10:13:34 浏览:487
服务器如何添加联想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