Skip to content

Instantly share code, notes, and snippets.

@viralsavani
Created March 22, 2017 04:31
Show Gist options
  • Select an option

  • Save viralsavani/7955735d49a8814f5b68bb7835fa23ab to your computer and use it in GitHub Desktop.

Select an option

Save viralsavani/7955735d49a8814f5b68bb7835fa23ab to your computer and use it in GitHub Desktop.
Image Loading Backoff
// Originally appeared in https://android-developers.googleblog.com/2017/03/getting-santa-tracker-into-shape.html
// Naive way to load bitmap
private LruCache<Integer, Drawable> mMemoryCache;
private BitmapFactory.Options mOptions;
public void init() {
// Initialize the cache
mMemoryCache = new LruCache<Integer, Drawable>(240);
// Start with no Bitmap sampling
mOptions = new BitmapFactory.Options();
mOptions.inSampleSize = 1;
}
public void loadBitmap(@DrawableRes int id) {
// Load bitmap
Bitmap bmp = BitmapFactory.decodeResource(getResources(), id, mOptions);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bmp);
// Add to cache
mMemoryCache.put(id, bitmapDrawable);
}
// However the decodeResource function will throw an OutOfMemoryError if we don't have
// enough RAM to load the Bitmap into memory. To combat this, we catch these errors
// and then try to reload all of the images with a higher sampling ratio (scaling by a factor of 2 each time):
private static final int MAX_DOWNSAMPLING_ATTEMPTS = 3;
private int mDownsamplingAttempts = 0;
private Bitmap tryLoadBitmap(@DrawableRes int id) throws Exception {
try {
return BitmapFactory.decodeResource(getResources(), id, mOptions);
} catch (OutOfMemoryError oom) {
if (mDownSamplingAttempts < MAX_DOWNSAMPLING_ATTEMPTS) {
// Increase our sampling by a factor of 2
mOptions.inSampleSize *= 2;
mDownSamplingAttempts++;
}
}
throw new Exception("Failed to load resource ID: " + resourceId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment