Can I catch out of memory exception in Android in Bitmap allocation for decoding a picture file?
Asked Answered
P

1

6

I tried to put a catch around the picture file decoding, but it fails to catch the out of memory exception, and the app crashes.

I know some tricks in decode a picture file, such as subsampling. But I need to zoom in the picture to see details, so I cannot subsample it too much. For some newer devices, it can succeed to allocate a larger memory to avoid the out of memory exception.

For some older devices, it cannot.

If I can customize my applicaiton for different devices, that would be greate.

So I want: (1) I hope I can catech the out of memory exception, so in case I catch it, I can reduce the image size. (2) Or, I hope I can get the size of available memory for allocation.

I search online, fail to find answers.

Passe answered 16/7, 2013 at 1:1 Comment(2)
Remember that even if you successfully catch the OutOfMemoryException, you are still low on memory, and there's no guarantee that your Activity or the Dalvik VM would not do something to push the memory over limit again, at which point the exception can be thrown from literately anywhere. Even if it seems to work on the devices you've tested, it'd still be a very dangerous practice.Monotony
First, being able to catch OutOfMemroy Exception, does not cause the app crash, which is what I desired. Second, if at some time point and for some device, it can allocate a large amount of size of memory, I would like to let the user has a better using experience, witch is still useful; in case memory is limited, then I will let the resolution lower. In any case, cathing or knowing memory issue is useful.Passe
C
5

First, you can see in the stack trace where the OutOfMemoryError was thrown. If you did not catch it, it is either because a) you were catching Exception instead of Throwable, or b) the error was thrown somewhere else than where you had the catch statement. With OutOfMemoryError you can't guarantee where it is going to be thrown. Usually it is where you are dealing with the bitmap, but it could be another thread that happens to allocate memory at the same time.

Getting the available memory on the device is trivial: http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass()

The Android team has a great set of articles on bitmaps and memory if you haven't seen them yet: http://developer.android.com/training/displaying-bitmaps/index.html

Good luck!

Castlereagh answered 16/7, 2013 at 1:26 Comment(3)
Thank you! I catched Throwable.Passe
how did you catch throwableUranology
I guess he catched it just like Exception: try { } catch(Throwable t) { t.printStackTrace(); }Heterogynous

© 2022 - 2024 — McMap. All rights reserved.