Reputation: 299
I've come across a strange problem - I'm making an android game and noticed a lag every few seconds and checked the logs when I noticed the garbage collector was being called every few seconds for 50-150ms a go.
I've whittled this problem down to the images, when I launch my title screen activity, using one background image (150kb) - the messages i get are:
4% free (8009k/8259k) GROW HEAP to 9.012MB GC_CONCURRENT freed 1kb (9178k/9479k)
Which is a lot of heap space for an image and three buttons. When I remove the image, I get no warnings or messages (not sure how to force an output on heap-space, but I hope it's at normal levels)
The code for the activity image isn't that exciting as it's just a title screen, but:
<ImageView
android:id="@+id/backgroundImage1"
android:contentDescription="Image"
android:src="@drawable/openingscreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
/>
When I launch the actual game the heap size increases again (only by a few mb's) -- the weird thing is when I didn't have the title screen, the heap space for the main game was still 12 or so mb's - so I'm thinking maybe the image is holding a reference to everything else. Although I tried using a background image of 1 pixel in size and this caused no problems.
Secondly, the code for images inside the gameThread:
mPlayer = Bitmap.createScaledBitmap(mPlayer, mCanvasWidth / 15, mCanvasHeight / 8, true);
canvas.drawBitmap(mPlayer, xPosition, yPosition, null);
I did hear somewhere that scaling bitmaps can cause memory problems, but that doesn't really add up with everything else.
Upvotes: 0
Views: 1620
Reputation: 299
Just updating, I found out the main problem in my code and managed to get it running smoothly, I doubt anybody else is stupid enough to make the same mistake but I'll post my solution just in case!
I was re-sizing my images every iteration of the game, I somehow didn't realize I put the code in there, changed it so it re-sizes them at the very start and that's it. But there it is, I doubt this solution will help anybody, but perhaps one day it will!
Kevin.
Upvotes: 0
Reputation: 371
Yes,a lot of developers while developing has faced this situation.
What i would ask you to do is a thorough study check of what exactly this heap is,how the garbage collector handles it,how can you efficiently use or even scale bitmaps
You could first start with going through this video Google Android Memory Management
Next in the android developers site, go through in detail Displaying bitmaps efficiently
Last and final thing start a habit of using MAT(Memory analyzer Tool),there are tutorials,lessons a lot of blogs on how to use it and finding out where and why the app is being deprived of memory
Upvotes: 1
Reputation: 28162
Following formular tells you how much heap space an image take: width x height x 8 bytes. So an image thats all white but large in size will still take a lot of heap space.
Upvotes: 0