Skip to content Skip to sidebar Skip to footer

Don't Invoke Push Notification When App Is Being Used (running In Foreground)

In my android app, I receive push notifications via Firebase Cloud Messaging. The notifications work completely fine, the only problem is that I don't want to receive notifications

Solution 1:

What I do is use ActivityLifeCycleCallbacks in your Application class

classMyApplication:Application(){
companionobject {
        privatevar activitiesOpen = 0var displayActivity:String?= nullprivatesetfunisAppOpen() = activitiesOpen > 0
    }
    privateval activitiesListener = object : ActivityLifecycleCallbacks{
        overridefunonActivityPaused(activity: Activity?) {
            --activitiesOpen
            displayActivity = null
        }

        overridefunonActivityResumed(activity: Activity?) {
            activitiesOpen++
            displayActivity = if(activity != null)
                activity::class.simpleName elsenull
        }

        overridefunonActivityStarted(activity: Activity?) {
        }

        overridefunonActivityDestroyed(activity: Activity?) {
        }

        overridefunonActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
        }

        overridefunonActivityStopped(activity: Activity?) {
        }

        overridefunonActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
        }
    }

}

Now in your onMessageReceived you can check it out like this.

    if (MyApplication.isAppOpen() &&
                DashboardActivity::class.simpleName?
.equals(MyApplication.displayActivity) ?: false) {
// you can eliminate the last condition if you wishplayAlertTone(context) // or whatever
        } else {
           // your notification building code
        }

The code is in kotlin, I hope you'll have no problem with it.

Post a Comment for "Don't Invoke Push Notification When App Is Being Used (running In Foreground)"