• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Managing Bitmap Memory
2parent.title=Displaying Bitmaps Efficiently
3parent.link=index.html
4
5trainingnavtop=true
6
7@jd:body
8
9<div id="tb-wrapper">
10<div id="tb">
11
12<h2>This lesson teaches you to</h2>
13<ol>
14  <li><a href="#recycle">Manage Memory on Android 2.3.3 and Lower</a></li>
15  <li><a href="#inBitmap">Manage Memory on Android 3.0 and Higher</a></li>
16</ol>
17
18<h2>You should also read</h2>
19<ul>
20  <li><a href="http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html">Memory Analysis for Android Applications</a> blog post</li>
21  <li><a href="http://www.google.com/events/io/2011/sessions/memory-management-for-android-apps.html">Memory management for Android Apps</a> Google I/O presentation</li>
22  <li><a href="{@docRoot}design/patterns/swipe-views.html">Android Design: Swipe Views</a></li>
23  <li><a href="{@docRoot}design/building-blocks/grid-lists.html">Android Design: Grid Lists</a></li>
24</ul>
25
26<h2>Try it out</h2>
27
28<div class="download-box">
29  <a href="{@docRoot}shareables/training/BitmapFun.zip" class="button">Download the sample</a>
30  <p class="filename">BitmapFun.zip</p>
31</div>
32
33</div>
34</div>
35
36<p>In addition to the steps described in <a href="cache-bitmap.html">Caching Bitmaps</a>,
37there are  specific things you can do to facilitate garbage collection
38and bitmap reuse. The recommended strategy depends on which version(s)
39of Android you are targeting. The {@code BitmapFun} sample app included with
40this class shows you how to design your app to work efficiently across
41different versions of Android.</p>
42
43<p>To set the stage for this lesson, here is how Android's management of
44bitmap memory has evolved:</p>
45<ul>
46  <li>
47On Android Android 2.2 (API level 8) and lower, when garbage
48collection occurs, your app's threads get stopped. This causes a lag that
49can degrade performance.
50<strong>Android 2.3 adds concurrent garbage collection, which means that
51the memory is reclaimed soon after a bitmap is no longer referenced.</strong>
52</li>
53
54  <li>On Android 2.3.3 (API level 10) and lower, the backing pixel data for a
55bitmap is stored in native memory. It is separate from the bitmap itself,
56which is stored in the Dalvik heap. The pixel data in native memory is
57not released in a predictable manner, potentially causing an application
58to briefly exceed its memory limits and crash.
59<strong>As of Android 3.0 (API level 11), the pixel data is stored on the
60Dalvik heap along with the associated bitmap.</strong></li>
61
62</ul>
63
64<p>The following sections describe how to optimize bitmap memory
65management for different Android versions.</p>
66
67<h2 id="recycle">Manage Memory on Android 2.3.3 and Lower</h2>
68
69<p>On Android 2.3.3 (API level 10) and lower, using
70{@link android.graphics.Bitmap#recycle recycle()}
71is recommended. If you're displaying large amounts of bitmap data in your app,
72you're likely to run into
73{@link java.lang.OutOfMemoryError} errors. The
74{@link android.graphics.Bitmap#recycle recycle()} method allows an app
75to reclaim memory as soon as possible.</p>
76
77<p class="note"><strong>Caution:</strong> You should use
78{@link android.graphics.Bitmap#recycle recycle()} only when you are sure that the
79bitmap is no longer being used. If you call {@link android.graphics.Bitmap#recycle recycle()}
80and later attempt to draw the bitmap, you will get the error:
81{@code &quot;Canvas: trying to use a recycled bitmap&quot;}.</p>
82
83<p>The following code snippet gives an example of calling
84{@link android.graphics.Bitmap#recycle recycle()}. It uses reference counting
85(in the variables {@code mDisplayRefCount} and {@code mCacheRefCount}) to track
86whether a bitmap is currently being displayed or in the cache. The
87code recycles the bitmap when these conditions are met:</p>
88
89<ul>
90<li>The reference count for both {@code mDisplayRefCount} and
91{@code mCacheRefCount} is 0.</li>
92<li>The bitmap is not {@code null}, and it hasn't been recycled yet.</li>
93</ul>
94
95<pre>private int mCacheRefCount = 0;
96private int mDisplayRefCount = 0;
97...
98// Notify the drawable that the displayed state has changed.
99// Keep a count to determine when the drawable is no longer displayed.
100public void setIsDisplayed(boolean isDisplayed) {
101    synchronized (this) {
102        if (isDisplayed) {
103            mDisplayRefCount++;
104            mHasBeenDisplayed = true;
105        } else {
106            mDisplayRefCount--;
107        }
108    }
109    // Check to see if recycle() can be called.
110    checkState();
111}
112
113// Notify the drawable that the cache state has changed.
114// Keep a count to determine when the drawable is no longer being cached.
115public void setIsCached(boolean isCached) {
116    synchronized (this) {
117        if (isCached) {
118            mCacheRefCount++;
119        } else {
120            mCacheRefCount--;
121        }
122    }
123    // Check to see if recycle() can be called.
124    checkState();
125}
126
127private synchronized void checkState() {
128    // If the drawable cache and display ref counts = 0, and this drawable
129    // has been displayed, then recycle.
130    if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed
131            && hasValidBitmap()) {
132        getBitmap().recycle();
133    }
134}
135
136private synchronized boolean hasValidBitmap() {
137    Bitmap bitmap = getBitmap();
138    return bitmap != null && !bitmap.isRecycled();
139}</pre>
140
141<h2 id="inBitmap">Manage Memory on Android 3.0 and Higher</h2>
142
143<p>Android 3.0 (API level 11) introduces the
144{@link android.graphics.BitmapFactory.Options#inBitmap BitmapFactory.Options.inBitmap}
145field. If this option is set, decode methods that take the
146{@link android.graphics.BitmapFactory.Options Options} object
147will attempt to reuse an existing bitmap when loading content. This means
148that the bitmap's memory is reused, resulting in improved performance, and
149removing both memory allocation and de-allocation. However, there are certain restrictions with how
150{@link android.graphics.BitmapFactory.Options#inBitmap} can be used. In particular, before Android
1514.4 (API level 19), only equal sized bitmaps are supported. For details, please see the
152{@link android.graphics.BitmapFactory.Options#inBitmap} documentation.
153
154<h3>Save a bitmap for later use</h3>
155
156<p>The following snippet demonstrates how an existing bitmap is stored for possible
157later use in the sample app. When an app is running on Android 3.0 or higher and
158a bitmap is evicted from the {@link android.util.LruCache},
159a soft reference to the bitmap is placed
160in a {@link java.util.HashSet}, for possible reuse later with
161{@link android.graphics.BitmapFactory.Options#inBitmap}:
162
163<pre>HashSet&lt;SoftReference&lt;Bitmap&gt;&gt; mReusableBitmaps;
164private LruCache&lt;String, BitmapDrawable&gt; mMemoryCache;
165
166// If you're running on Honeycomb or newer, create
167// a HashSet of references to reusable bitmaps.
168if (Utils.hasHoneycomb()) {
169    mReusableBitmaps = new HashSet&lt;SoftReference&lt;Bitmap&gt;&gt;();
170}
171
172mMemoryCache = new LruCache&lt;String, BitmapDrawable&gt;(mCacheParams.memCacheSize) {
173
174    // Notify the removed entry that is no longer being cached.
175    &#64;Override
176    protected void entryRemoved(boolean evicted, String key,
177            BitmapDrawable oldValue, BitmapDrawable newValue) {
178        if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
179            // The removed entry is a recycling drawable, so notify it
180            // that it has been removed from the memory cache.
181            ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
182        } else {
183            // The removed entry is a standard BitmapDrawable.
184            if (Utils.hasHoneycomb()) {
185                // We're running on Honeycomb or later, so add the bitmap
186                // to a SoftReference set for possible use with inBitmap later.
187                mReusableBitmaps.add
188                        (new SoftReference&lt;Bitmap&gt;(oldValue.getBitmap()));
189            }
190        }
191    }
192....
193}</pre>
194
195
196<h3>Use an existing bitmap</h3>
197<p>In the running app, decoder methods check to see if there is an existing
198bitmap they can use. For example:</p>
199
200<pre>public static Bitmap decodeSampledBitmapFromFile(String filename,
201        int reqWidth, int reqHeight, ImageCache cache) {
202
203    final BitmapFactory.Options options = new BitmapFactory.Options();
204    ...
205    BitmapFactory.decodeFile(filename, options);
206    ...
207
208    // If we're running on Honeycomb or newer, try to use inBitmap.
209    if (Utils.hasHoneycomb()) {
210        addInBitmapOptions(options, cache);
211    }
212    ...
213    return BitmapFactory.decodeFile(filename, options);
214}</pre
215
216<p>The next snippet shows the {@code addInBitmapOptions()} method that is called in the
217above snippet. It looks for an existing bitmap to set as the value for
218{@link android.graphics.BitmapFactory.Options#inBitmap}. Note that this
219method only sets a value for {@link android.graphics.BitmapFactory.Options#inBitmap}
220if it finds a suitable match (your code should never assume that a match will be found):</p>
221
222<pre>private static void addInBitmapOptions(BitmapFactory.Options options,
223        ImageCache cache) {
224    // inBitmap only works with mutable bitmaps, so force the decoder to
225    // return mutable bitmaps.
226    options.inMutable = true;
227
228    if (cache != null) {
229        // Try to find a bitmap to use for inBitmap.
230        Bitmap inBitmap = cache.getBitmapFromReusableSet(options);
231
232        if (inBitmap != null) {
233            // If a suitable bitmap has been found, set it as the value of
234            // inBitmap.
235            options.inBitmap = inBitmap;
236        }
237    }
238}
239
240// This method iterates through the reusable bitmaps, looking for one
241// to use for inBitmap:
242protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
243        Bitmap bitmap = null;
244
245    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
246        final Iterator&lt;SoftReference&lt;Bitmap&gt;&gt; iterator
247                = mReusableBitmaps.iterator();
248        Bitmap item;
249
250        while (iterator.hasNext()) {
251            item = iterator.next().get();
252
253            if (null != item && item.isMutable()) {
254                // Check to see it the item can be used for inBitmap.
255                if (canUseForInBitmap(item, options)) {
256                    bitmap = item;
257
258                    // Remove from reusable set so it can't be used again.
259                    iterator.remove();
260                    break;
261                }
262            } else {
263                // Remove from the set if the reference has been cleared.
264                iterator.remove();
265            }
266        }
267    }
268    return bitmap;
269}</pre>
270
271<p>Finally, this method determines whether a candidate bitmap
272satisfies the size criteria to be used for
273{@link android.graphics.BitmapFactory.Options#inBitmap}:</p>
274
275<pre>static boolean canUseForInBitmap(
276        Bitmap candidate, BitmapFactory.Options targetOptions) {
277
278    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT) {
279        // From Android 4.4 (KitKat) onward we can re-use if the byte size of
280        // the new bitmap is smaller than the reusable bitmap candidate
281        // allocation byte count.
282        int width = targetOptions.outWidth / targetOptions.inSampleSize;
283        int height = targetOptions.outHeight / targetOptions.inSampleSize;
284        int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
285        return byteCount &lt;= candidate.getAllocationByteCount();
286    }
287
288    // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
289    return candidate.getWidth() == targetOptions.outWidth
290            && candidate.getHeight() == targetOptions.outHeight
291            && targetOptions.inSampleSize == 1;
292}
293
294/**
295 * A helper function to return the byte usage per pixel of a bitmap based on its configuration.
296 */
297static int getBytesPerPixel(Config config) {
298    if (config == Config.ARGB_8888) {
299        return 4;
300    } else if (config == Config.RGB_565) {
301        return 2;
302    } else if (config == Config.ARGB_4444) {
303        return 2;
304    } else if (config == Config.ALPHA_8) {
305        return 1;
306    }
307    return 1;
308}</pre>
309
310</body>
311</html>
312