0

Please, I have 2 sheets and 1 Popover that I try to trigger through Firebase Messaging with the key: notification_type programmed in Kotlin.

When the app is running, the badge appears with a whitish icon but when you click on it, the Sheet or Popover does not appear.

And, when the app is closed, the app’s main logo just appears on top notification bar without any badge but, it triggers the sheet and popover to appear when you open it.

I have tried to set the priority for the Firebase notification to HIGH, hoping it would bring the badge.

And secondly, I have the sheets and popover wrapped in a different file called HSMApp and linked to MainActivity which triggers the sheet or popover I want through Firebase. But, when the app is open, it does not show.

MAINACTIVITY:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialize Firebase
        FirebaseApp.initializeApp(this)

        if (!checkPermissions()) {
            requestPermissions()
        }
        val notificationType: String? = intent.getStringExtra("notification_type")
        Log.d("MainActivity", "Received notification_type: $notificationType")

        setContent {
            // Pass the notification extra to HSMApp.
            HSMApp(notificationType = notificationType)
        }

    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent) // Ensure the new intent is used

        val notificationType: String? = intent.getStringExtra("notification_type")
        Log.d("MainActivity", "New Intent notification_type: $notificationType")

        setContent {
            HSMApp(notificationType = notificationType)
        }
    }

MYFIREBASEMESSAGING:


class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        // Check if the message contains notification payload
        remoteMessage.notification?.let {
            showNotification(it.title, it.body, remoteMessage.data["type"])
        }

        // Check if the message contains data payload
        if (remoteMessage.data.isNotEmpty()) {
            val title = remoteMessage.data["title"]
            val message = remoteMessage.data["message"]
            val type = remoteMessage.data["type"] // Expected: "devotional", "quiz", "word_for_the_day"

            if (!type.isNullOrEmpty()) {
                handleFirebaseEvent(type)
                showNotification(title, message, type) // Ensure notification is displayed for data messages
            } else {
                showNotification(title, message, null)
            }

        }
    }

    private fun handleFirebaseEvent(type: String) {
        // Create an explicit intent using our constant, then broadcast it.
        val intent = Intent(NOTIFICATION_TRIGGER_ACTION).apply {
            putExtra("type", type)
        }
        sendBroadcast(intent)
    }

    private fun showNotification(title: String?, message: String?, type: String?) {
        val channelId = "default_channel_id"
        val channelName = "Default Channel"
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Create a notification channel with high importance for heads-up notifications
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "Default channel for app notifications"
                enableLights(true)
                enableVibration(true)
            }
            notificationManager.createNotificationChannel(channel)
        }

        // Make sure the Intent correctly passes "notification_type"
        val intent = Intent(this, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
            putExtra("notification_type", type)
        }

        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.logo_image)  // Ensure this icon is white on transparent background
            .setColor(Color.parseColor("#660d77"))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            // For pre-Oreo devices, set high priority.
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            // Use defaults for sound, vibration, etc.
            .setDefaults(NotificationCompat.DEFAULT_ALL)

        notificationManager.notify(0, notificationBuilder.build())
    }

    override fun onNewToken(token: String) {
        Log.d("MyAppFCM", "New token: $token")
        sendTokenToServer(token)
    }

    private fun sendTokenToServer(token: String) {
        Log.d("FCM", "Firebase token: $token")
        // TODO: Implement API call to send the token to your backend
    }
}

HSMApp:

HSMAppTheme {
        MainScreen(
            onDismiss = {
                isDevotionalSheetVisible = false
                isQuizSheetVisible = false
                isWordPopupVisible = false
                isMailSheetVisible = false
            },
            showDevotionalSheet = { isDevotionalSheetVisible = true },
            showQuizSheet = { isQuizSheetVisible = true },
            showWordPopup = { isWordPopupVisible = true },
            showMailSheet = { isMailSheetVisible = true } // Add this
        )



        if (isDevotionalSheetVisible) {
            DevotionalSheet(onDismiss = { isDevotionalSheetVisible = false })
        }
        if (isQuizSheetVisible) {
            QuizSheet(onDismiss = { isQuizSheetVisible = false })
        }
        if (isWordPopupVisible) {
            WordForTheDayPopup(onDismiss = { isWordPopupVisible = false })
        }

4
  • This typically depends on the message type you send. See firebase.google.com/docs/cloud-messaging/…. If your message only contains a notification and no data key, then the behavior seems expected as your custom code is not executed in that case. Commented Mar 13 at 23:45
  • Please, can you elaborate more? I send the Notification Title and Notification Text along with the key: notification_type and add the value in Firebase Messaging. But it only works if the app is closed. Much explanation would be much appreciated as I am new to this, please. 🙏🏻
    – Phela
    Commented Mar 14 at 7:05
  • From the elaborate at the link: "For [Notification messages] FCM SDK displays the message to end-user devices on behalf of the client app when it's running in the background. Otherwise, if the app is running in the foreground when the notification is received, the app's code determines the behavior." Isn't that precisely what you describe? Commented Mar 14 at 15:31
  • I see, please. Thank you kindly. Will try to look into that by GOD’S Grace.
    – Phela
    Commented Mar 14 at 19:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.