Android bitmaps and out of memory errors

本文讲述了在Android中正确处理Bitmap的方法,特别是如何通过调用.recycle()方法来手动释放不再使用的Bitmap所占用的内存,这对于避免内存泄漏和提高应用程序性能至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One of the things I had to learn the hard way on Android is the correct way of handling Bitmaps. And honestly, I wouldn’t have thought this is the right way if someone at Google wouldn’t have suggested it to me.
Every time you create a bitmap, either blank or from a source using BitmapFactory, the full size of that bitmap is loaded into memory. If you have a 24bit, 300×300 pixel bitmap, it will use 24*300*300 bytes, which is approximately 2Mb. Handling that kind of memory allocated in the java heap space would be slow, so the Android engineers came with the smart solution of allocating and managing that memory natively (using C).
Now, if you know just a little C, you’ll know that all memory allocations have to be done manually, and so are the de-allocations (freeing up the memory). And since java doesn’t have destructors, when would the Bitmap objects you have know how to clear that memory? They simply don’t, so you need to clear that memory manually, by calling the .recycle() method of your bitmap object. Simple yet game-changing trick.
How you keep track of the bitmaps is up to you, but (just like all of the other variables), avoid using statics. If you REALLY need global objects, extend Application and keep your stuff there.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值