Friday, October 5, 2018

How to handle loading and keeping many bitmaps in an Android 2D game


In an Android 2D game which is using SurfaceView where its onDraw is driven by a loop from a Thread, I use many bitmap sprites (sprite sheets) and two background size bitmaps, which are all loaded into memory at the start.


It all works fine, however, when the activity is onPause or after reloading it few times, Android shows a tendency to wipe out the big bitmaps only, probably to free memory. Sometimes this happens even in the middle of loading this very activity.


In order to counter this, I made a check in the onDraw method to test if the big bitmaps are still there and reload them if they are forcefully recycled by Android, before drawing them on Canvas.


This solution may not be the most stable, and since I know that there are much more accomplished android game programmers here than myself, I hope you can reveal some tricks or secrets or at least provide some good hints, how to overcome this.



Answer



The way to do it:




  • never create any new bitmaps unless you don't really have to, check every bit of the code





  • set the Activity on RGB_565, and especially the SurfaceView





getHolder().setFormat(0x00000004); //RGB_565




  • load bitmpas with




options.inPreferredConfig = Bitmap.Config.RGB_565;



RGB_565 is good enough for images with many details and SurfaceView runs almost twice faster in frame rates



  • use ARGB_4444 for small images in drop down lists etc, or anything that does not require very good quality


Have not had any out of memory errors in the same game after implementing this.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...