Thursday, January 19, 2017

Android How to check App is in Background or Foreground

In some case, you might want to check your app is running in background or foreground, such as you want to show push notification message only when the app is in background. The following method will be very easy to know app running state.




First, add the GET_TASKS permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Then use the below method to check if app running is in background or foreground. This method will return true if app running is in background.


private boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

Good luck!
Share:

0 comments:

Post a Comment

Total Pageviews