Android management Bitmap memory-development document translation

Source: Internet
Author: User

Managing Bitmap Memory manages Bitmap Memory In addition to the steps described in Caching Bitmaps, there are specific things you can do to facilitate garbage collection and bitmap reuse. the recommended strategy depends on which version (s) of Android you are targeting. the BitmapFun sample app has ded with this class shows you how to design your app to work efficiently extends SS different versions of Android. besides As described in Caching Bitmaps, there are also some specific things that will help garbage collection and bitmap reuse. The suggested policies depend on your Android version. The BitmapFun sample application contains this class, which shows you how To design your application To make cross-version work more efficient To set the stage for this lesson, here is how Android's management of bitmap memory has evolved: lays the foundation for the course. below is how the bitmap memory management of android evolved On Android 2.2 (API level 8) and lower, when garbage collection occurs, your app's threads get stopped. this causes a lag that can degrade performance. android 2.3 adds concurrent garbage collection, which means that The memory is reclaimed soon after a bitmap is no longer referenced. In Android2.2 (API 8) and earlier versions, your application thread stops when garbage collection occurs. This will lead to latency, reducing performance. Android2.3 adds concurrent garbage collection. This means that when a bitmap is no longer referenced, the memory will soon be reclaimed On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. it is separate from the bitmap itself, which is stored in the Dalvik heap. the pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. A S of Android 3.0 (API Level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap. in Android 2.3.3 (API 10) and earlier versions, bitmap's pixel data is stored in native memory and is independent of bitmap itself, bitmap is the pixel data of bitmap stored in the native memory in the Dalvik heap. It is not released in a predictable behavior, which may cause the application memory to exceed the limit and crash in android3.0 (API 11) in, The bitmap pixel data is stored in The Dalvik heap, And The bitmap is associated with The following sections describe how to optimize bitmap memory management for different Android v Ersions. the following sections describe how to optimize bitmap Memory management Manage Memory on android 2.3.3 and Lower in different Android versions to Manage Memory On Android 2.3.3 (API level 10) in android2.3.3 and earlier versions) and lower, using recycle () is recommended. if you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. the recycle () method allows an app to reclaim memory as soon as possible. in android2.3.3 and earlier versions, we recommend that you use r Ecycle () If You display a large amount of bitmap data in your application, You are likely to get the OutOfMemoryError recycle () method to allow an application to reclaim the memory as soon as possible. Caution: You should use recycle () only when you are sure that the bitmap is no longer being used. if you call recycle () and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap ". note: You should use recycle () only when you are sure that this bitmap will not be used again. If you call recycle () and then try to draw this bitmap, you will get the error: "Canvas: trying To use a recycled bitmap "The following code snippet gives an example of calling recycle (). it uses reference counting (in the variables mDisplayRefCount and mCacheRefCount) to track whether a bitmap is currently being displayed or in the cache. the code recycles the bitmap when these conditions are met: The following code snippet provides an example of calling recycle () which uses reference count (in the variable mDisplayRefCount and mCacheRefCount) A bitmap in the root is currently being displayed or cached. The condition for code to recycle bitmap is: The reference count for both mDisplayRefCount and mCacheRefCount is 0.The bitmap is not null, and it hasn't been recycled yet. both the reference count mDisplayRefCount and mCacheRefCount must be = 0bitmap is not null, and it has not been recycled [java] private int mCacheRefCount = 0; private int mDisplayRefCount = 0 ;... // configure y the drawable that the displayed state has changed. // Keep a count to determine when the drawable is no long Er displayed. public void setIsDisplayed (boolean isDisplayed) {synchronized (this) {if (isDisplayed) {mDisplayRefCount ++; mHasBeenDisplayed = true;} else {mDisplayRefCount --;}} // Check to see if recycle () can be called. checkState ();} // configure y the drawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. public void setIsCached (B Oolean 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 & hasValidBitm Ap () {getBitmap (). recycle () ;}} private synchronized boolean hasValidBitmap () {Bitmap bitmap = getBitmap (); return bitmap! = Null &&! Bitmap. isRecycled ();} Manage Memory on Android 3.0 and Higher Manage Memory Android 3.0 (API Level 11) introduces the BitmapFactory in android3.0 and later versions. options. inBitmap field. if this option is set, decode methods that take the Options object will attempt to reuse an existing bitmap when loading content. this means that the bitmap's memory is reused, resulting in improved performance, and removing both memor Y allocation and de-allocation. there are some caveats in using inBitmap: Android3.0 (API 11) introduced BitmapFactory. options. if this option is set for inBitmap, when the content is loaded, the decoding method of the Options object will try to reuse an existing bitmap, which means that the memory of bitmap is reused, as a result, the performance is improved, and there is no need to allocate or re-allocate memory to use inBitmap. Note the following: the reused bitmap must be of the same size as the source content (to make sure that the same amount of memory is used), and in JPEG or PNG format (whether as a reso Urce or as a stream ). the size of the reused bitmap must be the same as that of the source content (ensure that the same memory is used), and it must be in JPEG or PNG format (as resource or stream) the configuration of the reused bitmap overrides the setting of inPreferredConfig, if set. you shoshould always use the returned bitmap of the decode method, because you can't assume that reusing the bitmap worked (for example, if there is a size mismatch ). save a bitmap for later use if inPreferredConfig is set, the reused bitmap You should use the bitmap returned by the decoding function in the total number of inPreferredConfig, because you cannot assume that the reused bitmap can work (for example, if the size does not match) save a bitmap The following snippet demonstrates how an existing bitmap is stored for possible later use in the sample app. when an app is running on Android 3.0 or higher and a bitmap is evicted from the LruCache, a soft reference to the bitmap is placed in a HashSet, for possible reuse later with inBitmap: the following code snippet demonstrates how In use, how can an existing image be stored for future use? When an application runs in andoid3.0 or a later version, and LruCache has recycled bitmap, to reuse inBitmap in the future, a soft reference of bitmap is stored in HashSet. [Java] HashSet <SoftReference <Bitmap> mReusableBitmaps; private LruCache <String, BitmapDrawable> mMemoryCache; // If you're running on Honeycomb or newer, create // a HashSet of references to reusable bitmaps. if (Utils. hasHoneycomb () {mReusableBitmaps = new HashSet <SoftReference <Bitmap> ();} mMemoryCache = new LruCache <String, BitmapDrawable> (mCacheParams. memCacheSize) {// configure y the removed e Ntry that is no longer being cached. @ Override protected void entryRemoved (boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) {if (recyclgbitmapdrawable. class. isInstance (oldValue) {// The removed entry is a reconfiguring drawable, so every y it // that it has been removed from the memory cache. (recyclic gbitmapdrawable) oldValue ). setIsCached (false);} else {// The rem Oved 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 <Bitmap> (oldValue. getBitmap ()));}}}....} use an existing bitmap to Use an existing bitmapIn the running app, decoder methods check to see if there is an existing bitmap they can Use. for example: in a running application, the decoding method checks whether there is an existing bitmap available For [java] 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 () {addInBitmapOptio Ns (options, cache );}... return BitmapFactory. decodeFile (filename, options);} The next snippet shows the addInBitmapOptions () method that is called in the above snippet. it looks for an existing bitmap to set as the value for inBitmap. note that this method only sets a value for inBitmap if it finds a suitable match (your code shoshould never assume that a match will be found ): the following code snippet shows the addI called in the above Code NBitmapOptions () method it looks for an existing bitmap as the value of inBitmap. Note that this method only sets inBitmap, if an appropriate match is found (your code should not assume this match will certainly be found) [java] 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 () {final Iterator <SoftReference <Bitmap> 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, this method determines whether a candidate bitmap satisfies the size criteria to be used for inBitmap: Finally, this method determines whether an alternative bitmap meets the inBitmap size standard [java] private static boolean canUseForInBitmap (Bitmap candidate, BitmapFactory. options targetOptions) {int width = targetOptions. outWidth/targetOptions. inSampleSize; int height = targetOptions. outHeight/targetOptions. inSampleSize; // Returns true if "candidate" can be used for inBitmap re-use with // "targetOptions ". return candidate. getWidth () = width & candidate. getHeight () = height ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.