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