How can I fix frequent Out Of Memory Errors on Android emulators?

◇◆丶佛笑我妖孽 提交于 2019-12-04 15:08:18

You either truly have run out of heap space, or the heap is sufficiently fragmented that Android cannot allocate whatever you are requesting. This will happen on production devices as well, and so treating this as an emulator issue is a mistake IMHO.

I'd start by doing more testing with the 4.x emulator. Partly, that will give you better crash information, including how large of an allocation failed. Partly, it will give you substantially better results when using MAT to figure out where your heap is going.

There are umpteen zillion questions and answers here on StackOverflow regarding OutOfMemoryError with bitmap allocation. You may wish to browse through some. They will point you in the same basic directions:

  • On Android 3.0+, use inBitmap on the BitmapOptions that you pass to BitmapFactory, to reuse existing memory as opposed to allocating new memory

  • recycle() your Bitmap objects when you are done with them

  • Be generally careful about your memory allocations, as Android's garbage collector is non-compacting, so eventually you will be incapable of allocating large blocks of memory again

  • Use MAT to see if you are leaking memory somewhere that is contributing to your problem

And so on.

Have a look at this Developer's Guide.

Use this workflow while decoding bitmap from external source:

private Bitmap decodeFile(File f, int reqHeight, int reqWidth){
    try {
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(o.outWidth/scale/2>=reqWidth && o.outHeight/scale/2>=reqHeight)
            scale*=2;

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}

    return null;
}

The important part is the inJustDecodeBounds.

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