Skip to content

Instantly share code, notes, and snippets.

@duanhong169
Created March 26, 2013 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duanhong169/5244099 to your computer and use it in GitHub Desktop.
Save duanhong169/5244099 to your computer and use it in GitHub Desktop.
private DiskLruCache mDiskLruCache;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
private static final String DISK_CACHE_SUBDIR = "disk_cache";
File cacheDir = getDiskCacheDir(this, DISK_CACHE_SUBDIR);
new InitDiskCacheTask().execute(cacheDir);
class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
@Override
protected Void doInBackground(File... params) {
synchronized (mDiskCacheLock) {
File cacheDir = params[0];
mDiskLruCache = DiskLruCache.open(cacheDir, DISK_CACHE_SIZE);
mDiskCacheStarting = false; // 初始化完成
mDiskCacheLock.notifyAll();
}
return null;
}
}
public void addBitmapToCache(String key, Bitmap bitmap) {
// 首先将图片加入到内存缓存中
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
// 将图片加入到外部存储缓存中
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
mDiskLruCache.put(key, bitmap);
}
}
}
public Bitmap getBitmapFromDiskCache(String key) {
synchronized (mDiskCacheLock) {
// 等待外部存储缓存初始化
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
return mDiskLruCache.get(key);
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment