Проверьте полезную нагрузку уведомления в onMessageReceived()

# #android #firebase-cloud-messaging

Вопрос:

Я пытаюсь отправить уведомление о данных в свое приложение, а затем использовать содержащиеся в нем данные для открытия фрагмента:

 override fun onMessageReceived(message: RemoteMessage) {

    Timber.d("onMessageReceived")

    try {

        val data = message.data

        if (data != null amp;amp; (data.containsKey(KEY_MSG) || data.containsKey(KEY_URL))) {

            val url = data[KEY_URL]

            if (!url.isNullOrEmpty()) {
                val clickAction = message.notification?.clickAction
                val intent = Intent(clickAction)
                intent.putExtra(KEY_URL, url).putUseStateExtra(UseState(UseState.COME_FROM_NOTIFICATION)).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            } else {
                sendNotification(data)
            }


        }
    } catch (e: Throwable) {
        Timber.e(e, "We didn't send the notification because ${e.message}")
    }
}
 

Затем я после вызова onMessageReceived() создаю уведомление и отправляю его следующими методами. Один для анализа полезной нагрузки:

 private fun sendNotification(data: Map<String, String>) {

    Timber.d("Notification sent: $data type: ${data[KEY_CLOUD8_TYPE]}")

    if (Interactors.preferences.notificationsEnabled == true) {

        Timber.d(data.toString())
        val title = data[KEY_TITLE]
        val msg = data[KEY_MSG]
        var cloud8Type = data[KEY_CLOUD8_TYPE] ?: ""
        var notificationType = data[NOTIFICATION_TYPE] ?: ""
        val campaignId = (data[KEY_CAMPAIGN_ID] ?: "0")
        val url = data[KEY_URL]

        if (!url.isNullOrBlank()) {
            cloud8Type = Cloud8Type.Link
        }
        sendNotification(title, msg, cloud8Type, notificationType, campaignId, url)
    }
}
 

Один для создания уведомления:

 private fun sendNotification(title: String?, message: String?, cloud8Type: String, notificationType: String, offerId: String, url: String?) {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    val channelId = "Main"

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notificationChannel = NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH)

        // Configure the notification channel.
        notificationChannel.description = "Channel description"
        notificationChannel.enableVibration(true)
        notificationManager.createNotificationChannel(notificationChannel)
    }

    val pendingIntent = getNotificationIntent(cloud8Type, notificationType, offerId, url)
    val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val notificationBuilder = NotificationCompat.Builder(this, channelId)
    notificationBuilder.setSmallIcon(R.drawable.ic_notification)
    notificationBuilder.setContentTitle(title)
    notificationBuilder.setContentText(message)
    notificationBuilder.setAutoCancel(true)
    notificationBuilder.setSound(defaultSoundUri)
    notificationBuilder.setContentIntent(pendingIntent)
    notificationManager.notify(0, notificationBuilder.build())
}
 

И два, чтобы использовать содержимое полезной нагрузки для создания намерения:

 private fun getNotificationIntent(cloud8Type: String, notificationType: String, offerId: String, url: String?): PendingIntent {

    Timber.d("Notification type: $cloud8Type}")

    val useState = UseState(UseState.COME_FROM_NOTIFICATION)
    val intent = getNotificationIntent(this, cloud8Type, notificationType, useState, offerId, url = url)

    return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

internal fun getNotificationIntent(
        context: Context,
        cloud8Type: String?,
        notificationType: String,
        useState: UseState,
        offerId: String?,
        url: String?
    ): Intent {

        var intent = Intent()
        when (cloud8Type) {
            Cloud8Type.NewOffer, Cloud8Type.NewChallengeOffer, Cloud8Type.Link ->
                intent = StartActivity.newInstance(context, useState, offerId, url)

            Cloud8Type.DailyEarning, Cloud8Type.YouDidIt, Cloud8Type.FundsTransfered, Cloud8Type.OfferPayment, Cloud8Type.OfferDonation -> {
                intent = if (Interactors.preferences.the8CloudSdkInfo.showPayoutTab) {
                    openSponsorTree(context, useState, ASponsorTree.TAB_PAYOUT, null)
                } else {
                    APayoutMain.newIntent(context)
                }
            }
            Cloud8Type.NewOffers ->
                intent = openSponsorTree(context, useState, ASponsorTree.TAB_FEED, null)


            else -> {
                when (notificationType) {
                    NotificationType.Payment -> intent = openSponsorTree(context, useState, ASponsorTree.TAB_PAYOUT, null)
                }
            }
        }



        return intent
    }
 

Я пытаюсь отладить полезную нагрузку, получаемую при получении уведомления, но ни одна из моих инструкций журнала не отображается при закрытии приложения. Есть ли какой-нибудь способ увидеть, что возвращается с RemoteMessage в onMessageReceived()? Есть ли что-нибудь еще, что я должен знать о том, как достичь того, чего я хочу достичь?

Комментарии:

1. Итак, когда приложение открыто на переднем плане, вы получаете уведомления, как onMessageReceived это называется? Но когда он помещен в фоновом режиме или вышел, вы этого не делаете?

2. Да, именно это и происходит.

Ответ №1:

Я добавил атрибут «уведомление» к полезной нагрузке и присвоил ему значение click_action, а затем перехватил его в своем начальном действии.

Ответ №2:

Пожалуйста, не отправляйте свои полезные данные в атрибуте уведомления. Это произойдет только тогда, когда приложение находится на переднем плане. Для получения уведомления также в фоновом режиме вам необходимо отправить полезную нагрузку в атрибут данных, а не в уведомление.

Пример :

 {
    "condition": " Better now",
    "priority" : "normal",
    "time_to_live" : 0,,
    "data" : {
        "id" : 1,
        "text" : "text is here!",
        "link" : "www.gmail.com"
    }
}
 

Комментарии:

1. Я не могу перенаправить пользователя, используя атрибуты только в столбце «данные». Мне также нужно действие click_action в атрибуте уведомления.

2. Вы также можете добавить параметр click_action вместе с ним