Memory Used by android to manage bitmap
In addition to caching bitmap, you can also do other things to optimize the reuse of GC and bitmap. The recommended policy depends on the Android system version. The example in the attachment shows you how to design an app to improve the memory performance of the app in different Android versions. In different Android versions, bitmap memory management is different. In Android2.2 (api level8) and earlier versions, when GC is triggered, the main thread of the App stops. This will cause an obvious lag and reduce the user experience. Concurrent GC has been added since Android2.3, which means that as long as bitmap is no longer referenced, the memory will be recycled immediately. In Android2.3.3 (api level 10) and earlier versions, the pixel data of bitmap is stored in the underlying memory, while bitmap itself is saved in the heap of the virtual machine. The collection of pixel data stored in the underlying memory is unpredictable, which may easily cause the App to exceed the memory limit and crash. After Android3.0, bitmap and associated pixel data are stored in the heap of the VM. The following describes how to optimize bitmap memory in different Android versions. 1. Manage the memory in Android2.3.3 and earlier versions. In Android 2.3.3 and earlier versions, we recommend that you use the recycle () method to manage the memory. If a large image is displayed in the App, it may cause an OutOfMemoryError. The recycle () method allows the APP to reclaim memory as soon as possible. Note that the recycle () method can be called only when you confirm that bitmap will not be used again. If you want to display a bitmap that has already called the recycle () method, you will get the Canvas: trying to use a recycled bitmap "exception. The following code snippet shows an example of calling the recycle () method. Here we use the reference count method to track the bitmap (variable mDisplayRefCount and mCacheRefCount) that is currently being displayed and in the buffer ). Image recycling is performed when the following two conditions are met. 1) mDisplayRefCount and mCacheRefCount are both 0. 2) bitmap is not null and the recycle () method has not been called.
Private int mCacheRefCount = 0; private int mDisplayRefCount = 0 ;... // The display status of drawable changes. // Keep a count to determine when the drawable is no longer displayed. public void setIsDisplayed (boolean isDisplayed) {synchronized (this) {if (isDisplayed) {mDisplayRefCount ++; mHasBeenDisplayed = true;} else {mDisplayRefCount --;}} // Check to see if recycle () can be called. checkState ();} // specify y the d Rawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. public void setIsCached (boolean isCached) {synchronized (this) {if (isCached) {mCacheRefCount ++;} else {mCacheRefCount -- ;}// Check to see if recycle () can be called. checkState ();} private synchronized void checkState () {// If the drawable cache and display ref counts = 0, and This drawable // has been displayed, then recycle. if (mCacheRefCount <= 0 & mDisplayRefCount <= 0 & mHasBeenDisplayed & hasValidBitmap () {getBitmap (). recycle () ;}} private synchronized boolean hasValidBitmap () {Bitmap bitmap = getBitmap (); return bitmap! = Null &&! Bitmap. isRecycled ();}2. Manage Android3.0 and later memoryThe BitmapFactory. Options. inBitmap field is added to Android3.0 (API level 11. If this option is set, the decode method using this option will try to reuse an existing bitmap to load the new bitmap. This means that bitmap memory will be reused to avoid allocating and releasing memory to improve performance. Then, there are some restrictions on using inBitmap. Especially before Android4.4 (API level19), this feature can only be used by bitmap with the same size. The following code snippet shows how to save an existing bitmap in the APP for future reuse. The APP runs in Android3.0 and later versions. When bitmap is released by LruCache, A HashSet is used to hold a soft reference of the bitmap for future reuse through inBitmap.
Set
> mReusableBitmaps;private LruCache
mMemoryCache;// If you're running on Honeycomb or newer, create a// synchronized HashSet of references to reusable bitmaps.if (Utils.hasHoneycomb()) { mReusableBitmaps = Collections.synchronizedSet(new HashSet
>());}mMemoryCache = new LruCache
(mCacheParams.memCacheSize) { // Notify the removed entry that is no longer being cached. @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache. ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable. if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later. mReusableBitmaps.add (new SoftReference
(oldValue.getBitmap())); } } }....}
During APP running, the following method checks whether bitmap can be reused.
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) { final BitmapFactory.Options options = new BitmapFactory.Options(); ... BitmapFactory.decodeFile(filename, options); ... // If we're running on Honeycomb or newer, try to use inBitmap. if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } ... return BitmapFactory.decodeFile(filename, options);}
The addInBitmapOptions () method in the above Code is implemented as follows. It is used to find an existing bitmap to set the inBitmap field. Note that this method will only set the inBitmap field if a suitable bitmap is found (your code should not assume that a match can always be found ).
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } }}// This method iterates through the reusable bitmaps, looking for one // to use for inBitmap:protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { Bitmap bitmap = null; if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator
> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap. if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used again. iterator.remove(); break; } } else { // Remove from the set if the reference has been cleared. iterator.remove(); } } } } return bitmap;}
Finally, the following method is used to determine whether the current bitmap meets the size requirements of inBitmap.
static boolean canUseForInBitmap( Bitmap candidate, BitmapFactory.Options targetOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); return byteCount <= candidate.getAllocationByteCount(); } // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1;}/** * A helper function to return the byte usage per pixel of a bitmap based on its configuration. */static int getBytesPerPixel(Config config) { if (config == Config.ARGB_8888) { return 4; } else if (config == Config.RGB_565) { return 2; } else if (config == Config.ARGB_4444) { return 2; } else if (config == Config.ALPHA_8) { return 1; } return 1;}