I need to check if the app is foreground
or background
to display incoming notifications either in the tray or in the app. Currently I have done it using RunningTaskInfo
but this requires the permission of: android.permission.GET_TASKS
which is deprecated. Any help is much appreciated!
My current method of checking
public static 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;
}
EDIT - The solution
So this is the solution I ended up going with. Thanks to /u/Dima Kozhevin for pointing me to the right post. This is the post: How to detect when an Android app goes to the background and come back to the foreground which I ended up modifying a little. The code I added is to check whether the screen is on or not. I did it the following way:
@Override
public void onActivityPaused(Activity activity) {
PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
if (!isInBackground) {
if (!pm.isScreenOn()) {
isInBackground = true;
Log.e(TAG, "app went to background");
}
}
}
I ran this solution on 3 different devices which all ended up working. If anyone finds anything that ends up breaking this, please let me know!