views:

37

answers:

2

I have created a simple test game that randomly spawns icons that move around the screen. When you click on an icon, it disappears. I used sample code from SDK, and various internet sites.

I want to change the background, it is being set to BLACK. I would like to use a picture I have.

 public void onDraw(Canvas canvas) {
       canvas.drawColor(Color.BLACK);
...
}

The background color is set on the onDraw. If I try to draw a bitmap instead, the game will eventually crash from a memory problem. (it runs out of memory). I believe this is because the image is being drawn every time onDraw is called.

I have tried placing it in various locations, but maybe I'm just missing something. Any help would be great. Below is the code I am using to create the background. My ideal goal would be to only create the background once at the start. And be able to update it when called for.

 Bitmap Background = BitmapFactory.decodeResource(getResources(),R.drawable.background);
 DisplayMetrics dm = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(dm);
 int height = dm.heightPixels;
 int width = dm.widthPixels;
 Rect rec = new Rect(0, 0, width, height);
 canvas.drawBitmap(Background, null, rec, null);
A: 

Each time you call BitmapFactory.decodeResource() I believe you get a new Bitmap object. So this means a new byte[]. Each time your draw is called another byte array is allocated. It is important to call recycle() on a Bitmap after you are done with it to signal that this byte[] can be dealloc'd. So in your current implementation after the draw just call, Background.recycle();

It is not an immediate dealloc so you may run into some performance issues. So you might also want to keep the single byte array in memory. Without more detail into where in the application this is happening it's hard to give advice on how to do this. However if this code is in the draw() method for a particular component, just create the Bitmap in the constructor of the component and use it in the draw() method. Then before you forget about the component make sure to call recycle on the bitmap instance.

Greg
When I added the recycle command, it did indeed stop it from crashing. Unfortunately, it made the game run very slowly. I decided to change the code up. and Place the New Bitmap code outside the onDraw as a public. Seems it has done the trick, game is running smooth and doesn't crash. Thanks for everyones help.
naradlov
you can accept an answer if you would like ;)
Greg
A: 

Another thing to consider, in addition to what Greg has posted, is the way in which Android handles orientation changes. Every time the screen orientation is changed, you activity will be destroyed and then be recreated. If the proper precautions are not taken, this can also result in a memory leak.

Take a look at: http://developer.android.com/resources/articles/avoiding-memory-leaks.html

phobos51594