Android - Reliable way to get percentage of heap size occupied

与世无争的帅哥 提交于 2019-12-12 03:19:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!