How to get running process list and traffic statistics

Today we got little application which displays list of working applications on Android in a ListView. When a process name is clicked application displays information about amount of data that application used – traffic info. We present following topics here:
- Display data in a form of ListView
- Display process list and their traffic statistics

Display data in a form of ListView


We want an icon and text to display in a ListView. Our layout looks like this.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000">

    <ImageView
        android:id="@+id/detailsIco"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_search" />
    
    <TextView
        android:id="@+id/appNameText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="APP NAME GOES HERE">
    </TextView>
</LinearLayout>

Next we need a ListAdapter which is responsible for building a list raw.

ListAdapter.java

package com.itcuties.apps.TransferUsageApp.adapters;

import java.util.List;

import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.itcuties.apps.TransferUsageApp.R;

public class ListAdapter extends ArrayAdapter<RunningAppProcessInfo> {
	// List context
	private final Context context;
	// List values
	private final List<RunningAppProcessInfo> values;

	public ListAdapter(Context context, List<RunningAppProcessInfo> values) {
		super(context, R.layout.main, values);
		this.context = context;
		this.values = values;
	}

	
	/**
	 * Constructing list element view
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = inflater.inflate(R.layout.main, parent, false);
		
		TextView appName = (TextView) rowView.findViewById(R.id.appNameText);
		appName.setText(values.get(position).processName);
		
		return rowView;
	}	
}


Display process list and their traffic statistics


Now we are ready to display processes and traffic information. Since we use ListView and which is responsive our activity will extend ListActivity to add functionality of performing action when an item is clicked – we override onListItemClick method.

MainActivity.java

package com.itcuties.apps.TransferUsageApp;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ListActivity;
import android.net.TrafficStats;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.itcuties.apps.TransferUsageApp.adapters.ListAdapter;

public class MainActivity extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get running processes
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> runningProcesses = manager.getRunningAppProcesses();
		if (runningProcesses != null && runningProcesses.size() > 0) {
			// Set data to the list adapter
			setListAdapter(new ListAdapter(this, runningProcesses));
		} else {
			// In case there are no processes running (not a chance :))
			Toast.makeText(getApplicationContext(), "No application is running", Toast.LENGTH_LONG).show();
		}

	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		long send 		= 0;
		long recived 	= 0;
		// Get UID of the selected process
		int uid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).uid;
		
		// Get traffic data
		recived = TrafficStats.getUidRxBytes(uid);
		send = TrafficStats.getUidTxBytes(uid);
		
		// Display data
		Toast.makeText(getApplicationContext(), "UID " + uid + " details...\n send: " + send/1000 + "kB" + " \n recived: " + recived/1000 + "kB", Toast.LENGTH_LONG).show();
	}

}

Full code of this application is available here.

18 Responses to "How to get running process list and traffic statistics"

  1. Philip says:

    I believe I am in the right environment. Its time to config and deploy…

    Reply
  2. D25 says:

    How can I hide the system processes, like System UI or Package Access Helper?

    Sorry for my English :)

    Reply
    • itcuties says:

      Hi D25,
      if you want to hide the system processes from the list just remove everything that has the name starting with com.android and system from the runningProcesses.
      RunningAppProcessInfo.processName contains the name of the process.

      Take care,
      itcuties

      Reply
  3. Jitendra says:

    how we can get the battery consumption information by an app can u give me some sample example for it or solution thnx

    Reply
  4. elKsa says:

    HI. excelent post, everything worked just fine. Though I have a doubt. What is the meaning of the data you show when clicking the process, KBs sent and KBs received?

    Thanks i advance.

    Reply
  5. Jose says:

    How Do I close a process of this list ?
    and How Do I get the cache for each App?

    Reply
    • itcuties says:

      Hello,
      According to the documentation this should do the trick (place this code in the MainActivity. onListItemClick):

      int pid = ((RunningAppProcessInfo)getListAdapter().getItem(position)).pid;
      Process.sendSignal(pid, Process.SIGNAL_KILL); // or Process.killProcess(pid);
      
      

      But it seems that the only application that you can close is the one that calls this code. Do you maybe know why?
      What do you mean by getting App’s cache?
      itcuties

      Reply
      • itcuties says:

        Ok, case solved :)

        This code, when put in the MainActivity.onListItemClick kills the process

        String processName = ((RunningAppProcessInfo)getListAdapter().getItem(position)).processName;
        ActivityManager activityManager = (ActivityManager)getSystemService("activity");
        activityManager.killBackgroundProcesses(processName);
        

        To use it you need this permission in your AndroidManifest.xml file

        <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
        
        Reply
  6. ankish says:

    hey ,

    When i run this code on any phone , not only this code. But other samples across the net. I always get 0 rec and 0 sent for all the apps.
    Anyone know whats the problem?

    Reply
  7. ashwani says:

    This makes total sense . But i have query , how can i print all the process running from one application ? i.e if my application contains lot process which is included in manifest file . like below :

    and so on …..
    So , is it possible to print these services also ?? With above code, it will just print the main process but not the services which are added in manifest file .
    Note : These service start as soon as my application is launched (verified by adb shell ps)
    Kindly help

    Reply
    • itcuties says:

      When adding xml to the comment please use [xml]YOUR XML HERE[/xml].

      Reply
      • ashwani says:

        i am sorry , here is my missing xml from above comment

          <service android:name="org.abc.SandboxedProcessService1"
                         android:process=":sandboxed_process1"
                         android:isolatedProcess="true"
                          />
         <service android:name="org.abc.SandboxedProcessService1"
                         android:process=":sandboxed_process2"
                         android:isolatedProcess="true"
                          />  

        and so on …..

        Reply
  8. erum says:

    can someone pls help me how can i find memory usage for each process how much memory is consumed by each process by passing pid or package name to the methods and also what is the meaning of active processes or deactive process ?

    Reply
  9. Bilal says:

    Hello, i want to show the traffic stats constantly in front of everylist item without showing it in to toast ,plz help me with the code changing i am beginner

    Reply
  10. lee says:

    How can I get the traffic of the portal hotspot I shared on my android phone? I have got the UID of com.huawei.wifihotspot is 10047,Is it the process of portal hotspot ? If the answer is true,why the send and receive is always 0.Even I have used other phone connected this phone’s hotspot shared for a while and have scaned some news on browser.
    Sorry for my English

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>