Skip to content Skip to sidebar Skip to footer

Sending A Push Notification Only When App Is In Background

I use NotificationManager, NotificationChannel and NotificationCompat.Builder to display a push notification when an event is triggered, no online Firebase. The push notification

Solution 1:

I think you have FCMListenerService to receive your push notification as a background service. The Service should have the following declaration in the manifest file.

<serviceandroid:name=".Service.FCM.FCMListenerService"><intent-filter><actionandroid:name="com.google.firebase.MESSAGING_EVENT" /></intent-filter></service>

Now you can pass the context of this service alone to check if the application is in foreground or in background. The function for checking if the application is foreground is following.

privatestaticbooleanisForeground(Context context) {
    ActivityManagermanager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
    ComponentNamecomponentInfo= runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(Constants.ApplicationPackage);
}

Hence, in your onMessageReceived function you need to check if the application is in foreground and do not create the notification in the status bar.

publicclassFCMListenerServiceextendsFirebaseMessagingService {

    @OverridepublicvoidonMessageReceived(RemoteMessage message) {
        if(!isForeground(this)) createNotification();
    }
}

Hope that helps!

Solution 2:

So I found a proper and very good solution for this problem. According to this answer: https://stackoverflow.com/a/42679191/6938043

Application.ActivityLifecycleCallbacks

publicclassMainActivityChatsextendsAppCompatActivityimplementsApplication.ActivityLifecycleCallbacks 
{
    protectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getApplication().registerActivityLifecycleCallbacks(this);
    }

    publicvoidonActivityResumed(Activity activity)
    {
        if(msg_updater != null)
        {
            msg_updater.set_app_is_active(true);
        }

    }
    publicvoidonActivityPaused(Activity activity)
    {
        if(msg_updater != null)
        {
            msg_updater.set_app_is_active(false);
        }
    }

    publicvoidonActivityStopped(Activity activity) {}
    publicvoidonActivityCreated(Activity activity, Bundle bundle) {}
    publicvoidonActivityStarted(Activity activity) {}
    publicvoidonActivitySaveInstanceState(Activity activity, Bundle bundle) {}
    publicvoidonActivityDestroyed(Activity activity) {}
}

Post a Comment for "Sending A Push Notification Only When App Is In Background"