开发者

OutOfMemoryException: bitmap exceeds VM budget

开发者 https://www.devze.com 2023-03-21 08:14 出处:网络
I uploaded an app (Hungry Birds) to the marketplace and a friend downloaded it for his Xperia x10. He开发者_如何学运维 changed the Bitmap from the default, non-animated version to an animated one, and

I uploaded an app (Hungry Birds) to the marketplace and a friend downloaded it for his Xperia x10. He开发者_如何学运维 changed the Bitmap from the default, non-animated version to an animated one, and that's when the game crashed. I've intensively tested it on Nexus 1, HTC Magic, HTC Desire and an emulator, and they work fine everywhere else. Why does the Xperia do that? And is there a way to increase the VM budget on specific devices in the code?

EDIT: Exception is thrown when a resource (png) which is 200kb big is being created, although I mostly only use a smaller, cut-out portion of that (it's big for tablet support).

EDIT2: Strangely, the code worked on my dev phone (HTC Magic with 2.2 CyanogenMod) when I turned the heap size down to 12mb. As far as I know, the minimum is 16mb. Any ideas why that worked?

BTW: After I implemented the workaround, it suddenly started working on the X10, don't know why. Android is strange..


is there a way to increase the VM budget on specific devices in the code?

-This is not possible.

Only solution is to handle the outOfMemoryException in your code.

To avoid this outOfMemoryException you can follow these two simple things. Make your bitmap to be null on each cycle. And you can recycle your bitmap like this, bitmap.recycle(); once you have finished using your bitmap. This will remove the memory consumed by bitmap.


I had this problem several times. The only way I have found to solve this is to measure the amount of memory left on the device in order to scale down (not always possible) or use other kind of degraded modes.

I first get the amount of memory available:

final Runtime rt = Runtime.getRuntime();
final long freeMem = rt.freeMemory() + (rt.maxMemory() - rt.totalMemory());

And then I compare this to the size of my resource (can be an image, a sound, anything else...). I generally apply a ratio (from 0.50 to 0.80, but this is a matter of strategy) to avoid consuming all available memory.

if (myResourceSize < (freeMem * ratio)) { 
    // use it as it is
}
else {
    // use (or create if possible) something smaller
}
0

精彩评论

暂无评论...
验证码 换一张
取 消