首页 > 解决方案 > 如何从具有不同数据的通知中意图不同的活动?

问题描述

我的应用程序中有一些不同类型的操作,它们notifications分别使用 FCM 发送数据。数据大部分是相同的,所以我只使用一种带有数据模型类的sendNotification方法。我成功发送notifications,但我很困惑为他们设置意图操作,所以他们总是让我只关注 ChatActivity。这些通知是来自 ChatActivity 的消息通知、来自个人资料活动的好友请求通知和来自 CommentActivity 的评论通知。

private fun sendNotification(mRemoteMessage: RemoteMessage) {

        val user = mRemoteMessage.data["user"]
        val icon = mRemoteMessage.data["icon"]
        val title= mRemoteMessage.data["title"]
        val body = mRemoteMessage.data["body"]

        val notification = mRemoteMessage.notification
        val j = user!!.replace("[\\D]".toRegex(), "").toInt()
        val intent = Intent(this, ChatActivity::class.java)

        val bundle = Bundle()
        bundle.putString("userId", user)
        intent.putExtras(bundle)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

        val pendingIntent = PendingIntent.getActivity(this, j, intent, PendingIntent.FLAG_ONE_SHOT)

        val defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val builder : NotificationCompat.Builder = NotificationCompat.Builder(this)
                .setSmallIcon(icon!!.toInt())
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(defaultSound)
                .setContentIntent(pendingIntent)

        val noti = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        var i = 0

        if (j > 0){
            i=j
        }
        noti.notify(i, builder.build())

    }

标签: androidkotlinandroid-intentnotificationsfirebase-cloud-messaging

解决方案


简单的解决方案是添加一种通知类型,例如:new_message、add_friend、.. 因此,您可以使用该类型确定您想要传递的意图。例子:

if (type == "new_message") { 
 // let's new an intent of chat activity here
} else if (type == "add_friend") {
// let's new an intent of friend activity
}

然后像这样将意图放入待处理的意图中: val pendingIntent = PendingIntent.getActivity(this, j, intent, PendingIntent.FLAG_ONE_SHOT)


推荐阅读