A Java method to log Android memory use

As a quick note today, here’s a little Java method that I use to log Android memory use (RAM use) from an Activity or Fragment:

private void logMemoryInfo(Context context, String TAG) {
   ActivityManager activityManager = (ActivityManager) context.getSystemService(getActivity().ACTIVITY_SERVICE);
   int memoryClass = activityManager.getMemoryClass();
   ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
   activityManager.getMemoryInfo(memoryInfo);

   Log.i(TAG, "\n------------ RAM -------------");
   Log.i(TAG, "mem class: " + memoryClass);
   Log.i(TAG, "mem avail: " + memoryInfo.availMem);
   Log.i(TAG, "low mem:   " + memoryInfo.lowMemory);
   Log.i(TAG, "threshold: " + memoryInfo.threshold);

   long mb = 1024*1024;
   Runtime runtime = Runtime.getRuntime();
   Log.i(TAG, "Used Memory:  " + (runtime.totalMemory() - runtime.freeMemory()) / mb);
   Log.i(TAG, "Free Memory:  " + runtime.freeMemory()  / mb);
   Log.i(TAG, "Total Memory: " + runtime.totalMemory() / mb);
   Log.i(TAG, "Max Memory:   " + runtime.maxMemory()   / mb);
}

As you can see I log the memory/RAM use in several different ways.

Assuming that you put this code in a class named Utils, to use this method, just call it from your Android code like this, being sure to pass in the logging TAG from your Android class:

Utils.logMemoryInfo(TAG);

I’ll add more of an interpretation of these RAM values as I understand them better, but for today I just thought I’d share this source code.

Related: The last portion of that method is based on my example of how to show Scala application memory use.