Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 607
user1914692 Avatar asked Jul 16 '13 01:07

user1914692


1 Answers

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!

like image 109
enl8enmentnow Avatar answered Oct 10 '22 10:10

enl8enmentnow