The way I mentioned below is a very efficient way to get the total spent time of an app by a user in android. First of all you need to a custom ActivityLifecycleCallbacks which is responsible to trigger out when the application began to start and when stop. You need to just register the ActivityLifecycleCallbacks to your application instance. This will also care about if any user pauses the app so you don't need to think about it.The custom ActivityLifecycleCallbacks class is -
public class ApplicationTimeSpentTracker implements Application.ActivityLifecycleCallbacks {
private int activityReferences = 0;
private boolean isActivityChangingConfigurations = false;
private long startingTime;
private long stopTime;
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
startingTime=System.currentTimeMillis()/1000; //This is the starting time when the app began to start
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
stopTime = System.currentTimeMillis() / 1000;//This is the ending time when the app is stopped
long totalSpentTime= stopTime-startTime; //This is the total spent time of the app in foreground
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
Finally you need to register the callback to your application instance in MainActivity like this -
activity.getApplication().registerActivityLifecycleCallbacks(new ApplicationTimeSpentTracker());
Here is my post if you need details