Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See Android recent task executed by the user

Tags:

android

pid

task

I would like to watch the recent task of my android phone. I was trying some code from internet but non of them work properly. I just want to get the PID and Name of the last application executed by the user. For example, if I execute the calculator application and after that the recent task application that I made, this application shoul be able to tell me something like: "the last application you've executed is 'calculator' and the PID is '2222'".

I was checking on Android developers web page for some code and this is what I found, but I don't know how to implement for Android.

ActivityManager.RecentTaskInfo Information you can retrieve about tasks that the user has most recently started or visited.

ActivityManager.RunningServiceInfo Information you can retrieve about a particular Service that is currently running in the system.

any suggestion,

Best regards

ActivityManager.RunningTaskInfo Information you can retrieve about a particular task that is currently "running" in the system.

like image 634
Martin Solac Avatar asked Mar 11 '11 15:03

Martin Solac


2 Answers

int numberOfTasks = 1;
ActivityManager m = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
//Get some number of running tasks and grab the first one.  getRunningTasks returns newest to oldest
RunningTaskInfo task = m.getRunningTasks(numberOfTasks).get(0);

//Build output
String output  = "the last application you've executed is '"+task.id+"' and the PID is '"+task.baseActivity.toShortString()+"'";

getRunningTasks

RunningTaskInfo

like image 120
rgmills Avatar answered Oct 18 '22 17:10

rgmills


Here is my solution:

final   ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (int i = 0; i < recentTasks.size(); i++) 
    {
        Log.d("Executed app", "Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+"");         
    }

Be careful!!The last ID is not the PID of the process!! If you want to get the PID of the process I used the following command :

mLogcatProc = Runtime.getRuntime().exec(new String[] {"ps"}); 

Read the result finding the application name and then split to obtain PID process.

like image 42
Martin Solac Avatar answered Oct 18 '22 16:10

Martin Solac