How to check android applications’ CPU usage

I’m currently working on a project for which I need to read the CPU usage by applications. There are question and answers on this topic but I could’t find any tutorials on it so I decided to write one.

Basically, there are many things that you can’t do using the Java api, but, with a quick tweak you can. In order to read cpu usage of applications you will need to run a bash command on the device. Java Runtime class provides this feature for developers and is also supported by android’s java VM.

If you have basic bash knowledge you’d know that you can use the “top” command to see the list of running processes and their cpu and memory usage. If you’r not familiar with this command open a bash terminal and enter the command. You will notice that this will show you a list of processes and update them regularly. Since, we want maximum number of applications possible, we will use the following arguments on a android device.

 

The parameter “-m” corresponds to the number of processes to show. “-n” means only one iteration and “id” is the delay between processes. This will output something like the following.

You need to parse the output. The values above, each correspond to something about the application. The first value is the pid of the app.The last is its name. The third is the CPU usage which we want. The problem is that we will get a list of these outputs. We will need to limit these to what we want. In order to do that we can use the “grep” command and pass in the pid we need. Some thing like the following:

How to run this within your android application

The only problem is that we are using a pipe command “|” and pipes are a property of the shell and without it we can’t use it. Try the code above and you will fail. Therefore, we need to invoke the shell to. Therefore, we can use the following code:

 

 

2 comments On How to check android applications’ CPU usage

Leave a reply:

Your email address will not be published.

Site Footer