Skip to content Skip to sidebar Skip to footer

How To Detect And Count When Activity Goes From Background To Foreground

I want to detect and count when Activity goes from background to foreground (when activity is visible, increase count).I tried to use flag in onPause() and onResume() like this: vo

Solution 1:

Use this method to check wheter app is brought to background:

privatebooleanisApplicationBroughtToBackground(Context context) {
    ActivityManageram= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentNametopActivity= tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            returntrue;
        }
    }

    returnfalse;
}

It requires the GET_TASKS permission:

<uses-permissionandroid:name="android.permission.GET_TASKS" />

Post a Comment for "How To Detect And Count When Activity Goes From Background To Foreground"