0

The getRunningTasks method in ActivityManager would've worked perfectly, but it was deprecated in 21. What else can you do to get the foreground application, and then see how long it has been running in the foreground?

I've seen some variants, but all seem to be a roundabout way to do this.

Thanks.

wednesdaymiko
  • 283
  • 1
  • 9
  • 1
    This is no longer possible, unless there are privacy/security flaws floating around. You are welcome to [use `UsageStatsManager`](https://developer.android.com/reference/android/app/usage/UsageStatsManager.html) (with permission) to get some of this information. – CommonsWare Mar 27 '18 at 14:18

1 Answers1

0

I'd suggest using Application.ActivityLifecycleCallbacks interface. It allows you to listen whenever activity calls lifecycle method. You can than do sth like:

@Override
public void onActivityStarted(Activity activity) {
    if (startedActivities == 0) {
        //App is in foreground get start time, store it in variable
    }
    activityCounter++;
}

@Override
public void onActivityStopped(Activity activity) {
    startedActivities--;
   if (startedActivities == 0) {
        //App is in background, get stored time and here you go
    }
}

There are some other idea of detecting app moving to foreground/background but this is only one that was reliable in my app.

Check also this

Community
  • 1
  • 1
muminers
  • 1,190
  • 10
  • 19