I am writing a very memory intensive application for Android Honeycomb, and I've been very careful to recycle()
unused Bitmap
s wherever possible; indeed, this is necessary for the application to work at all, as Bitmap
s are constantly being cycled in and out of memory. However, I have just implemented onConfigurationChanged()
in the Activity
, and so (for a number of reasons) I am trying to put memory freeing routines in onStop()
.
Currently my onStop()
method:
- sets some
View
s to display a default Drawable
;
- calls
recycle()
on the Bitmap
s previously used by these View
s;
- nulls references to the
Bitmap
s.
Unfortunately, using the Eclipse memory profiler, it seems this is having no effect on the memory usage at all.
As you can imagine, having made so much effort to free resources in a nominally garbage-collected language, I would have hoped for a little more effect. So my question is: what does recycle()
do? Does it actually trigger garbage collection, or will the system hold on to the memory—even if you call System.gc()
—until it feels the need to get rid of something?
NB I know Bitmap
s aren't actually held in the regular heap but I thought calling recycle()
was enough to ensure they were dropped out of the native heap.
PART OF THE ANSWER
I have discovered that if an ImageView
contains a Bitmap
that has been recycled, the Bitmap
data is still retained in memory until setImageBitmap(null)
is called on the ImageView
. This may even be the case if setImageResource(...)
or setImageDrawable(...)
are called (they were, loading in a relatively small nine-patch—however, MAT analysis shows this did not remove the large Bitmap
, which was contained in the private members of the ImageView
). Simply calling this function at onStop()
has culled about 10MB from the heap of our application. Apparently this may not be the case for pre-Honeycomb builds of Android, though.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…