Skip to content

Instantly share code, notes, and snippets.

@bepcyc
Created January 30, 2012 12:59
Show Gist options
  • Save bepcyc/1704273 to your computer and use it in GitHub Desktop.
Save bepcyc/1704273 to your computer and use it in GitHub Desktop.
Logging Heap info in Android
/**
* Logging Heap Info for Android
* @source <a href="http://stackoverflow.com/a/8018476/918211">StackOverflow Thread</a>
*/
public static void logHeap(Class clazz) {
final String APP = "MyApp";
Double allocated = new Double(Debug.getNativeHeapAllocatedSize())/1048576d;
Double available = new Double(Debug.getNativeHeapSize())/1048576.0d;
Double free = new Double(Debug.getNativeHeapFreeSize())/1048576.0d;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
Log.d(APP, "debug. =================================");
Log.d(APP, "debug.heap native: allocated " + df.format(allocated) + "MB of " + df.format(available) + "MB (" + df.format(free) + "MB free) in [" + clazz.getName().replaceAll("com.myapp.android.","") + "]");
Log.d(APP, "debug.memory: allocated: " + df.format(new Double(Runtime.getRuntime().totalMemory() / 1048576)) + "MB of " + df.format(new Double(Runtime.getRuntime().maxMemory() / 1048576)) + "MB (" + df.format(new Double(Runtime.getRuntime().freeMemory() / 1048576)) + "MB free)");
System.gc();
System.gc();
// don't need to add the following lines, it's just an app specific handling in my app
if (allocated>=(new Double(Runtime.getRuntime().maxMemory())/new Double((1048576))-MEMORY_BUFFER_LIMIT_FOR_RESTART)) {
android.os.Process.killProcess(android.os.Process.myPid());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment