0

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

Damien Belard
  • 285
  • 3
  • 12
  • 1
    This won't work as of Android 5.0 or so. Google is locking this information down, more and more with each passing release, for privacy and security reasons. – CommonsWare Oct 07 '15 at 14:43
  • That's what i thought it used to work on a custom rom but not anymore on official. Thanks for the link I am going to try there solution. – Damien Belard Oct 07 '15 at 14:46

0 Answers0