问题
In one of my activities I load a large number of bitmaps dynamically and show them in a GridView. There is risk of exceeding the heap size and crashing the app. I need a reliable way to know when heap size is growing too large, to stop loading the bitmap and start recycling the ones now being viewed at the moment. I tried using this function:
public int memoryPercent(){
Double alloc=new Double(Runtime.getRuntime().totalMemory()/1048576);
Double avail=new Double(Runtime.getRuntime().maxMemory()/1048576);
double per= (alloc/avail)*100;
int pr=(int)per;
Log.e("Memory used",Integer.toString(pr));
return pr;
}
It returns a value that indeed increases when more bitmaps are loaded. But it does not decrease when bitmaps are recycled. What other options do I have ?
I have thought of calculating the byte size of each bitmap and add them to see their total size and then substruct those that are recycled trying to keep their total size under the value that Runtime.getRuntime().maxMemory() returns...But this sounds too messy. there has to be a better way
来源:https://stackoverflow.com/questions/26512276/android-reliable-way-to-get-percentage-of-heap-size-occupied