如何从具有不同数据的通知中意图不同的活动?

How to intent to different activities from notification with different data?

我的应用程序中有一些不同类型的操作,它们使用 FCM 分别发送 notifications 和它们的数据。数据大部分相同,所以我只使用一个 sendNotification 方法和数据模型 class。我成功发送了 notifications,但我很困惑如何将意图操作设置给他们,所以他们总是只让我发送 ChatActivity。这些通知是来自 ChatActivity 的消息通知、来自个人资料 activity 的好友请求通知和来自 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())

    }

简单的解决方案是添加一种通知,例如: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)