Skip to content

Instantly share code, notes, and snippets.

@sanjogshrestha
Created March 19, 2018 12:56
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 sanjogshrestha/ccbaa6492ecca2cf64614b59b7f6061b to your computer and use it in GitHub Desktop.
Save sanjogshrestha/ccbaa6492ecca2cf64614b59b7f6061b to your computer and use it in GitHub Desktop.
lru disk cache
/* class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
@Override
protected Void doInBackground(File... params) {
synchronized (mDiskCacheLock) {
File cacheDir = params[0];
try {
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, DISK_CACHE_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
mDiskCacheStarting = false; // Finished initialization
mDiskCacheLock.notifyAll(); // Wake any waiting threads
}
return null;
}
}
public void addBitmapToCache(String key, Bitmap bitmap) {
if (key == null || bitmap == null)
return;
// add to disk cache
synchronized (mDiskCacheLock) {
try {
if (mDiskLruCache != null && mDiskLruCache.get(key) == null) {
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
OutputStream os = editor.newOutputStream(0);
Bitmap.CompressFormat cp = Bitmap.CompressFormat.JPEG;
bitmap.compress(cp, 90, os);
os.flush();
editor.commit();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Bitmap getBitmapFromDiskCache(String key) {
if (key == null)
return null;
synchronized (mDiskCacheLock) {
// Wait while disk cache is started from background thread
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
try {
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
InputStream in = null;
Bitmap bitmap;
if (snapshot != null) {
in = snapshot.getInputStream(0);
bitmap = BitmapFactory.decodeStream(in);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// 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()) ||
!Environment.isExternalStorageRemovable() ? context.getExternalCacheDir().getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment