I need to show notification to user only if application is not in foreground. Here is my public class MyFirebaseMessagingService extends
FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { if(applicationInForeground()) { Map<String, String> data = remoteMessage.getData(); sendNotification(data.get("title"), data.get("detail")); } }
need to implement applicationInForeground()
method
Whenever a new activity is started and visible to the user its instance is updated in the application class: activeActivity variable, so we can use it to determine which activity is in the foreground from the notifications layer.
Foreground services are an advanced Android concept which allows you to display notifications to your users when running long lived background tasks. The notification acts like any other notification, however it cannot be removed by the user and lives for the duration of the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With