How to get current memory usage in android?

I have used /proc/meminfo and parsed command response.however it result shows that :

MemTotal: 94348 kB MemFree: 5784 kB

means. it shows there is only 5MB free memory. Is it possible with android mobile? There is only 5-6 application installed on my mobile and no other task is running. but still this command shows there is very little free memory.

Can somebody clarify this? or is there any other way of getting memory usage in android?

226641 次浏览

Linux's memory management philosophy is "Free memory is wasted memory".

I assume that the next two lines will show how much memory is in "Buffers" and how much is "Cached". While there is a difference between the two (please don't ask what that difference is :) they both roughly add up to the amount of memory used to cache file data and metadata.

A far more useful guide to free memory on a Linux system is the free(1) command; on my desktop, it reports information like this:

$ free -m
total       used       free     shared    buffers     cached
Mem:          5980       1055       4924          0         91        374
-/+ buffers/cache:        589       5391
Swap:         6347          0       6347

The +/- buffers/cache: line is the magic line, it reports that I've really got around 589 megs of actively required process memory, and around 5391 megs of 'free' memory, in the sense that the 91+374 megabytes of buffers/cached memory can be thrown away if the memory could be more profitably used elsewhere.

(My machine has been up for about three hours, doing nearly nothing but stackoverflow, which is why I have so much free memory.)

If Android doesn't ship with free(1), you can do the math yourself with the /proc/meminfo file; I just like the free(1) output format. :)

Another way (currently showing 25MB free on my G1):

MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;

CAUTION: This answer measures memory usage/available of the DEVICE. This is NOT what is available to your app. To measure what your APP is doing, and is PERMITTED to do, Use android developer's answer.


Android docs - ActivityManager.MemoryInfo

  1. parse /proc/meminfo command. You can find reference code here: Get Memory Usage in Android

  2. use below code and get current RAM:

    MemoryInfo mi = new MemoryInfo();
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    double availableMegs = mi.availMem / 0x100000L;
    
    
    //Percentage can be calculated for API 16+
    double percentAvail = mi.availMem / (double)mi.totalMem * 100.0;
    

Explanation of the number 0x100000L

1024 bytes      == 1 Kibibyte
1024 Kibibyte   == 1 Mebibyte


1024 * 1024     == 1048576
1048576         == 0x100000

It's quite obvious that the number is used to convert from bytes to mebibyte

P.S: we need to calculate total memory only once. so call point 1 only once in your code and then after, you can call code of point 2 repetitively.

Here is a way to calculate memory usage of currently running application:

public static long getUsedMemorySize() {


long freeSize = 0L;
long totalSize = 0L;
long usedSize = -1L;
try {
Runtime info = Runtime.getRuntime();
freeSize = info.freeMemory();
totalSize = info.totalMemory();
usedSize = totalSize - freeSize;
} catch (Exception e) {
e.printStackTrace();
}
return usedSize;


}

you can also use DDMS tool which is part of android SDK it self. it helps in getting memory allocations of java code and native c/c++ code as well.

I looked at Android Source Tree.

Inside com.android.server.am.ActivityManagerService.java (internal service exposed by android.app.ActivityManager).

public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
outInfo.availMem = Process.getFreeMemory();
outInfo.totalMem = Process.getTotalMemory();
outInfo.threshold = homeAppMem;
outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
outInfo.hiddenAppThreshold = hiddenAppMem;
outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
ProcessList.SERVICE_ADJ);
outInfo.visibleAppThreshold = mProcessList.getMemLevel(
ProcessList.VISIBLE_APP_ADJ);
outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
ProcessList.FOREGROUND_APP_ADJ);
}

Inside android.os.Process.java

/** @hide */
public static final native long getFreeMemory();


/** @hide */
public static final native long getTotalMemory();

It calls JNI method from android_util_Process.cpp

Conclusion

MemoryInfo.availMem = MemFree + Cached in /proc/meminfo.

Notes

Total Memory is added in API level 16.

It depends on your definition of what memory query you wish to get.


Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.

For this, you can check the next values:

final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)

That's also what the DDMS tool of memory usage shows.


Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.


Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:

val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize

But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.

So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.


EDIT: seems Debug.getNativeHeapSize() changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.

If you want to get the real total and available native RAM , use this:

val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
"free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
"used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")

I refer few writings.

reference:

This getMemorySize() method is returned MemorySize that has total and free memory size.
I don't believe this code perfectly.
This code is testing on LG G3 cat.6 (v5.0.1)

    private MemorySize getMemorySize() {
final Pattern PATTERN = Pattern.compile("([a-zA-Z]+):\\s*(\\d+)");


MemorySize result = new MemorySize();
String line;
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
while ((line = reader.readLine()) != null) {
Matcher m = PATTERN.matcher(line);
if (m.find()) {
String name = m.group(1);
String size = m.group(2);


if (name.equalsIgnoreCase("MemTotal")) {
result.total = Long.parseLong(size);
} else if (name.equalsIgnoreCase("MemFree") || name.equalsIgnoreCase("Buffers") ||
name.equalsIgnoreCase("Cached") || name.equalsIgnoreCase("SwapFree")) {
result.free += Long.parseLong(size);
}
}
}
reader.close();


result.total *= 1024;
result.free *= 1024;
} catch (IOException e) {
e.printStackTrace();
}


return result;
}


private static class MemorySize {
public long total = 0;
public long free = 0;
}

I know that Pattern.compile() is expensive cost so You may move its code to class member.

public static boolean isAppInLowMemory(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);


return memoryInfo.lowMemory;
}
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

It is a strange code. It return MaxMemory - (totalMemory - freeMemory). If freeMemory equals 0, then the code will return MaxMemory - totalMemory, so it can more or equals 0. Why freeMemory not used?

Here is another way to view your app's memory usage:

adb shell dumpsys meminfo <com.package.name> -d

Sample output:

Applications Memory Usage (kB):
Uptime: 2896577 Realtime: 2896577


** MEMINFO in pid 2094 [com.package.name] **
Pss  Private  Private  Swapped     Heap     Heap     Heap
Total    Dirty    Clean    Dirty     Size    Alloc     Free
------   ------   ------   ------   ------   ------   ------
Native Heap     3472     3444        0        0     5348     4605      102
Dalvik Heap     2349     2188        0        0     4640     4486      154
Dalvik Other     1560     1392        0        0
Stack      772      772        0        0
Other dev        4        0        4        0
.so mmap     2749     1040     1220        0
.jar mmap        1        0        0        0
.apk mmap      218        0       32        0
.ttf mmap       38        0        4        0
.dex mmap     3161       80     2564        0
Other mmap        9        4        0        0
Unknown       76       76        0        0
TOTAL    14409     8996     3824        0     9988     9091      256


Objects
Views:       30         ViewRootImpl:        2
AppContexts:        4           Activities:        2
Assets:        2        AssetManagers:        2
Local Binders:       17        Proxy Binders:       21
Death Recipients:        7
OpenSSL Sockets:        0


SQL
MEMORY_USED:        0
PAGECACHE_OVERFLOW:        0          MALLOC_SIZE:        0


For overall memory usage:

adb shell dumpsys meminfo

https://developer.android.com/studio/command-line/dumpsys#meminfo