I am building an app where I implemented a service to detect which app is actually running on foreground. I have written it like this:
public class TestService extends Service {
ActivityManager am = null;
private TimerTask mTask;
private Timer mTimer;
public TestService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("TestService", "onStartCommand");
am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
mTimer = new Timer();
initializeTimerTask();
mTimer.schedule(mTask, 1, 500);
return 0;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
private void initializeTimerTask(){
mTask = new TimerTask() {
@Override
public void run() {
List<ActivityManager.RunningAppProcessInfo> taskInfo = am.getRunningAppProcesses();
String currentRunningActivityName = taskInfo.get(0).processName;
Log.v("TestService", "" + currentRunningActivityName);
}
};
}
}
So from what I have read from other post, this piece of code:
List<ActivityManager.RunningAppProcessInfo> taskInfo = am.getRunningAppProcesses();
String currentRunningActivityName = taskInfo.get(0).processName;
is supposed to give me the package of the app actually on foreground, but it only return me the package on my own app.
If it can help, the service is launched at boot by a BroadcastReceiver