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

谁说胖子不能爱 提交于 2019-12-10 13:12:08

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/17666390/can-i-catch-out-of-memory-exception-in-android-in-bitmap-allocation-for-decoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!