Home > Software engineering >  How can I disable receiving notifications If the app is running in the Background? - Kotlin
How can I disable receiving notifications If the app is running in the Background? - Kotlin

Time:08-24

I want to add functionality to my App to disable and enable notifications. and for the notification I will use firebase cloud messaging "service push notifications" If the app is running in the foreground then I will check a variable "showNotification" in the onMessageReceived function to show the notifications or not

    if(showNotification) {
        if (remoteMessage.notification != null) {
            generateNot(
                remoteMessage.notification!!.title!!,
                remoteMessage.notification!!.body!!
            )
        }
    }

The challenge I have is when the app is running in the background and since notifications are only displayed by the system when the app is not active.

Is there a way to disable showing notifications if the app is running in the background when the variable showNotification is false ?

CodePudding user response:

I solved this problem using another method. you can override handleIntent instead of onMessageReceived. by using this method you are able to handle notification received from the firebase in foreground or background.

 override fun handleIntent(intent: Intent?) {
    val body = intent!!.getStringExtra("gcm.notification.body").toString()
    val title = intent.getStringExtra("gcm.notification.title").toString()


    try {
       if(isAppOnForeground()){
             // your app is running in the foreground
        }else {
             // your app is running in the background
        }
    } catch (e: Exception) {
        Log.e("handleIntent: ", e.toString())
    }
}

also you can get title and body using the code above. also with function below you can check if your app is in the background or not.

private fun isAppOnForeground(): Boolean {
        return ProcessLifecycleOwner.get().lifecycle.currentState
            .isAtLeast(Lifecycle.State.STARTED)
    }
  • Related