Android bitmaps and out of memory errors

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.

你可能感兴趣的:(android)