I'm looking into a way to tie a running task id into it's corresponding process ID (pid).
The context is a system service which is deployed as part of the platform that needs to monitor the current activity in the foreground, I can use the entire AOSP platform, but I cannot change it.
I have the following code in my service to get the activity stack:
private List<StackInfo> getStack() throws Exception
{
Log.i(TAG, "getStack");
List<StackInfo> stacks = null;
stacks = mAm.getAllStackInfos();
return stacks;
}
and this is the monitoring thread:
private class MonitorThread extends Thread
{
public void run()
{
while (true)
{
try
{
Log.i(TAG, "In MonitorThread");
Thread.sleep(1000);
StackInfo fore = getStack().get(0);
String name = fore.taskNames[fore.taskIds.length-1];
name = name.substring(0, name.indexOf("/"));
/* Next line is where I have the problem, I'm getting the task id (activity id) instead of the PID for the process */
Log.i(TAG, "Current FG PID: "+fore.taskIds[fore.taskIds.length-1] + " name: "+ name + "\n");
}
catch (Exception e)
{
Log.i(TAG, "---=== EXCEPTION!!! ===---");
Log.i(TAG, e.getMessage());
Log.i(TAG, "---=== END EXCEPTION!!! ===---");
}
}
}
}
These achieve the goal of getting the process name that is currently in the foreground by taking the top most activity name from the active stack and trimming the activity name from the result (e.g activity name com.example/MainActivity belongs to process com.example).
So far I have two methods of achieving this, both are far from ideal:
The bad way:
I can iterate every application in the system and look up the current activity in it's activity stack, once a match is found, I can use the application PID (inefficient, O(M) where M is the total number of tasks)The even worst way
The task names return as com.package.xxx/activity_name where the part preceding the '/' is the process name (as far as I can tell, anyhow). Once I have that, I can call 'ps | grep com.package.xxx' and parse the output for the PID (I really don't want shell calls)
All I can find online is how to get the opposite - all activities that belong to an application.
Anyone has a better idea? Thanks!