I have been building an Android game which loads, scales, and displays bitmaps. Whenever I start loading a batch of bitmaps, the memory profile of the game on my LG Nexus 4 skyrockets. Then when I start interacting with the game (touching the screen to walk, etc), the memory consumption drops radically, and then raises and drops small amounts with regularity as the tiles background scrolls by (images are unloaded as the drop off the screen).
I've recently added more bitmaps at a specific point in the game and it takes me all the way to 550 MB and then crashes with an out of memory error.
My art assets total less than 13 MB and I never have them all loaded at the same time. Why is my game consuming massive amounts of memory at certain points?
Here is my bitmap loading code:
public class BackgroundBitmapLoader implements Runnable {
public GameView gameView;
public BackgroundTile backgroundTile;
public Bitmap bitmap;
public int drawableID;
public Context context;
public int scaledWidth;
public int scaledHeight;
public BackgroundBitmapLoader(GameView gameView, BackgroundTile backgroundTile, Context context, int drawableID, int scaledWidth, int scaledHeight) {
this.gameView = gameView;
this.backgroundTile = backgroundTile;
this.context = context;
this.drawableID = drawableID;
this.scaledHeight = scaledHeight;
this.scaledWidth = scaledWidth;
}
public void run() {
bitmap = BitmapFactory.decodeResource(context.getResources(), drawableID);
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false);
backgroundTile.setBitmap(bitmap);
gameView.incrementLoadedBitmapCount();
}
}
And here is the code I use to unload bitmaps when they move off the screen or are no longer needed:
public class BitmapUnloader implements Runnable {
Bitmap bitmap;
public BitmapUnloader(Bitmap bitmap) {
this.bitmap = bitmap;
}
public void run() {
bitmap.recycle();
}
}