Is there any API by which we can get CPU or Memory usage of android?
I have tried one code as below:
package com.infostretch.mainactivity;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class CPULoad
{
long total = 0;
long idle = 0;
float usage = 0;
public CPULoad()
{
readUsage();
}
public float getUsage()
{
readUsage();
return usage;
}
private void readUsage()
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
String load = reader.readLine();
reader.close();
String[] toks = load.split(" ");
long currTotal = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
long currIdle = Long.parseLong(toks[5]);
this.usage = (currTotal - total) * 100.0f / (currTotal - total + currIdle - idle);
this.total = currTotal;
this.idle = currIdle;
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
Is this the correct way to do it?
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
Based on the previous answers and personnal experience, here is the code I use to monitor CPU use. The code of this class is written in pure Java.
There are several ways of exploiting this class. You can call either
syncGetSystemCpuUsage
orsyncGetProcessCpuUsage
but each is blocking the calling thread. Since a common issue is to monitor the total CPU usage and the CPU use of the current process at the same time, I have designed a class computing both of them. That class contains a dedicated thread. The output management is implementation specific and you need to code your own.The class can be customized by a few means. The constant
CPU_WINDOW
defines the depth of a read, i.e. the number of milliseconds between readings and computing of the corresponding CPU load.CPU_REFRESH_RATE
is the time between each CPU load measurement. Do not setCPU_REFRESH_RATE
to 0 because it will suspend the thread after the first read.I use this function to calculate cpu usage. Hope it can help you.
An easy way to check the CPU usage is to use the adb tool w/ top. I.e.:
adb shell top -m 10
Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?
Check the
Debug
class. http://developer.android.com/reference/android/os/Debug.html i.e.Debug.getNativeHeapAllocatedSize()
It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.
The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.
For CPU usage I'm not sure if there's anything available via API/SDK.