android – Why would I ever NOT use BitmapFactory's inPurgeable option?-ThrowExceptions

Exception or error:

Android’s BitmapFactory.Options.inPurgeable has been recommended in various places as a way to avoid OutOfMemory exceptions in Android 2.x and earlier (Android 3.1 fixes this).

If inPurgeable is so great, why would I ever NOT want to use it? The documentation seems very light on details about what this option is doing:

If this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory. In that instance, when the pixels need to be accessed again (e.g. the bitmap is drawn, getPixels() is called), they will be automatically re-decoded

Seems great. What’s the catch?

How to solve:

The documentation has subsequently been updated with additional information which addresses your original question.

Summary: use of this flag is no longer recommended.

###

If your are reading your bitmaps from the filesystem, using this flag wil force Android to keep the file open (at least in 4.0.4) to be able to re-read it. After reading more than 1024 files, you will reach the limit of opened files and get a “Too many open files” error.

You can observe the beahavior by using the lsof command from a rooted terminal and review all opened files.

###

This flag is currently completely ignored, that’s the catch.


Update by @slodge: please anyone who is reading this and seeing it as the correct answer also read the comments – ‘This flag is currently completely ignored’ is true in certain cases only – in other cases (e.g. when using decodeByteArray on downloaded data) then this flag is not ignored and is very, very useful

###

For the re-decode to happen, the bitmap must have access to the encoded data, either by sharing a reference to the input or by making a copy of it.

If you don’t have access to the encoded data anymore, then this could be a problem right? What if you were live decoding bitmaps from a streaming ByteArray and your application just decides to reclaim the memory, wouldn’t that cause your Bitmap to lose those pixels?

Leave a Reply

Your email address will not be published. Required fields are marked *