Getting this exception which forces the android app to crash on start

江枫思渺然 提交于 2019-11-30 16:41:47

You need to understand the concept of Bitmap and memory

Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory_needed_in_bytes = 4 * image_width * image_height;

Why 4? Well, the most common / recommended bitmap configuration is ARGB_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB_565 configuration that requires half the memory than ARGB_8888, but loses the transparency and the color precision (while maybe adding a green tint).

Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes * 4000 * 3000 = 48 MB

48 megabytes of your RAM just for a single image!? That’s a lot!

Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 * 1920 * 1080 = 8.3 MB of memory.

Always follow the Android programming tips for displaying bitmaps efficiently:

Measure the view you’re showing your images in. Scale / crop the large image accordingly. Show only what can be displayed.

The exception thrown is known as OutOfMemoryError. The error occurs when (obviously) you run out of memory! Here is the documentation for it:

Thrown when a request for memory is made that can not be satisfied using the available platform resources. Such a request may be made by both the running application or by an internal function of the VM.

More information here:

http://developer.android.com/reference/java/lang/OutOfMemoryError.html

So, you should allocate more memory to your emulator. But I think the main reason is your app uses too much memory. Did you use a super big image?

add this ligne to your manifest file:

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