问题
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