Android How to check app is in Foreground or background.

In some cases you might want to check whether you app is running in background or foreground. An example use case would be, you want to show push notification message only when the app is in background. The following method will be very useful 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 the app is in background or foreground. This method will return true if the app 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;     }

Source : AndroidHive

Leave a Reply