I'm writing an image manipulation tool and, for image quality reasons, want to edit the image in as large a size as possible.
I need to be careful that I don't run out of memory while my app is running. In addition, I want to take advantage of devices with lots of memory. For example, I'd like to support medium size images on less powerful devices like the G1 and let more powerful devices like the Samsung Galaxy S support large images.
Is there a reliable way to gauge how much memory my app can use?
My current idea is that, when deciding on the image size to load, the device could calculate the image size that brings memory usage for the app as close to about 70% as possible (i.e. not 100% as you don't want the app c开发者_如何学Pythonrashing on small allocations later or because of memory fragmentation)
I've found I can use the following code to return a percentage of the available memory:
double totalMemoryUsed = (Runtime.getRuntime().totalMemory() + android.os.Debug.getNativeHeapAllocatedSize());
int percentUsed = (int)(totalMemoryUsed / Runtime.getRuntime().maxMemory() * 100);
New bitmaps add to the native heap allocated part. This seems reliable in that my app will predictably crash with an out of memory error when percentUsed goes above 100%. Are there any caveats to the above calculation I need to be aware of?
Are there any caveats to the above calculation I need to be aware of?
My first thought is that you really can only rely on the accuracy of a calculation like that at the instant when you perform it. Android has all sorts of services and other applications that are running in the background. At any given instant, the amount of memory currently in use is going to change. There is no way to tell by how much until you perform a calculation again. Additionally, no two phones are going to be alike so you really can't accurately estimate it.
You would almost need a thread or async task recalculating this on a constant basis which I'm not sure is a good idea.
I would stray away from this, and consider building your app using a different strategy. But good luck to you if you continue to pursure it.
精彩评论