我能赶上内存溢出异常Android中的位图分配解码图片文件?位图、我能、异常、分配

2023-09-07 23:15:15 作者:烟酒情话。

我试图把一个catch周围的图片文件解码,但它未能赶上了内存异常,并且应用程序崩溃。

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.

我知道在去$ C $一些技巧℃的图片文件,如二次取样。但我需要在图片放大查看详细信息,所以我不能二次采样太多。对于一些较新的设备,它能够成功分配一个更大的内存,以避免内存不足的异常。

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.

所以,我想:(1)我希望我能在儿茶素内存溢出异常,所以在情况下,我抓住它,我可以缩小图像尺寸。(2)或者,我希望我能得到的可用内存大小分配。

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.

推荐答案

首先,你可以在那里的OutOfMemoryError抛出的堆栈跟踪看看。如果你没赶上它,它要么是因为:a)你捕捉异常,而不是Throwable的,或者b)被抛出其他地方比,你有catch语句的错误。随着OutOfMemoryError异常,你不能保证它是要被抛出。通常它是你正在处理位图,但它可能是另一个线程恰好在同一时间分配内存。

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.

获取设备上的可用内存很简单:http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass()

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

Android团队有一个伟大的一套关于位图和内存条,如果你还没有见到它们:http://developer.android.com/training/displaying-bitmaps/index.html

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

祝你好运!