0
votes

I have an android game that loads 6 images totaling 300kb. I've already read and implemented this article http://developer.android.com/training/displaying-bitmaps/load-bitmap.html and while it helped a little bit, it didn't solve my issue 100%.

When the game loads the first time it runs just fine. No errors or anything. Then when you close out of the game or press the home screen button and go back into the game later on it then presents the out of memory error, but only sometimes. In my on resume I'm only starting the game thread back up. I'm not loading in any images or anything like that. Surely I can't have the only game that loads 6 or more images?

My onResume

    @Override
    protected void onResume(){
        try{
            game.setIsPaused(false);
            game.startSounds();
            game.threadStart();
        super.onResume();
    }

Loading my images in its own thread

bg = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.bg, context, options), imgPercentWidth, imgPercentHeight);
overlay = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.overlay, context, options), imgPercentWidth, imgPercentHeight);
reel = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.reels, context, options), imgPercentWidth, imgPercentHeight);
payOutBG = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.payout, context, options), imgPercentWidth, imgPercentHeight);
achievement = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.achievement, context, options), imgPercentWidth, imgPercentHeight);

Methods to resize and create the bitmaps

public Bitmap createBitmap(int id, Context context, BitmapFactory.Options options){
    return BitmapFactory.decodeResource(context.getResources(), id, options);
}
public Bitmap resizeBitmapPercent(Bitmap bitmap, float w, float h){       
    float newWidth = bitmap.getWidth()*w;
    float newHeight = bitmap.getHeight()*h;
    float scaleWidth = (float) newWidth / bitmap.getWidth();
    float scaleHeight = (float) newHeight / bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    return Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
2
stackoverflow.com/questions/11418354/recycling-bitmaps. Recycling bitmaps may solve your problem. Check the link. - Raghunandan

2 Answers

0
votes

after closing the game always try to empty the bitmap

I usually use this code

bmp.recycle();
bmp = null;
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();

it'll recycle the bitmap and using garbage collector

0
votes

I was able to fix this by converting all my non transparent images from png to jpeg and lowering their quality to 60 in photoshop. It dropped my total image size from 300kb to 100ish kb. I was worried that the quality drop would look bad, but you couldn't tell there was any decrease in quality on either a smart phone or tablet.