Android: memory exception / How does decodeResource add VMs to the budget?

I am new to Android and developing a game. From time to time, I get users from memory exceptions, which I find amazing, since the bitmap images that I create have a size of no more than 200 kb. I call BitmapFactory.decodeResource()whenever I create a new one sprite. Since my application is a defense against zombies, you can expect me to create sprites quite often.

Every time I create a sprite, I call a decoding resource to create a bitmap. My question is, should I only call the decoding resource at the beginning of each activity and refer to the bitmap at the packet level, will the amount of memory allocated in the VM budget decrease?

+5
source share
2 answers
  • When decoding a bitmap image from an image resource such as png, it depends more on the size of the image, and not on the size in KB.
  • Try it if you can reduce the size of the original image without affecting the result.
  • Try reusing bitmaps, and then continue to decode them.
  • Explore more parameters with the BitmapFactory.Options () object, for example, increasing inSampleSize can reduce the amount of memory needed for the image. eg
    
    BitmapFactory.Options o=new BitmapFactory.Options();
    o.inSampleSize = 4;
    o.inDither=false;                     //Disable Dithering mode
    o.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
    myBitMap=BitmapFactory.decodeResource(getResources(),ID, o);
    
  • , , , OutOfMemoryException, max.. .. inSampleSize 16. , , MP .
+18

, . sampleSize ( sampleSize - ).

public static Bitmap loadBitmapSafety(int resDrId,  Context context){
    return loadBitmapSafety(resDrId, 1, context);
}

private static Bitmap loadBitmapSafety(int resDrId, int sampleSize, Context context){
    BitmapFactory.Options ops = new BitmapFactory.Options();
    ops.inSampleSize = sampleSize;

    try {
        return BitmapFactory.decodeResource(context.getResources(), resDrId, ops);

    } catch (OutOfMemoryError e) {
        if (sampleSize == 4)
            return null;
        return loadBitmapSafety(resDrId, sampleSize +1, context);

    } catch (Exception e){
        return null;
    }
}
0

All Articles