How to check is app in foreground from service?
You can control running app processes from android system service. Try this:
private boolean applicationInForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> services = activityManager.getRunningAppProcesses();
boolean isActivityFound = false;
if (services.get(0).processName
.equalsIgnoreCase(getPackageName()) && services.get(0).importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
isActivityFound = true;
}
return isActivityFound;
}
Good luck.
At Google I/O 2016, I gave a talk where one of the topics was how Firebase detects if your app is in the foreground. You can use ActivityLifecycleCallbacks for that by incrementing a counter for every activity in your app that gets started, then decrementing it for each activity that gets stopped. If the counter is > 1, then your app is in the foreground. The relevant part of the talk can be seen on YouTube here.