android - 如何从具有不同数据的通知中意图不同的活动?
问题描述
我的应用程序中有一些不同类型的操作,它们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())
}
解决方案
简单的解决方案是添加一种通知类型,例如: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)
推荐阅读
- android - 迁移到 androidX 后,OkHttp 帖子内容在发布版本中为空
- spring-boot - Spring-Boot 1.5.10.release 与 apache-kafka-2.3.0 客户端的兼容性
- android - 使用特定的物理相机 ID 而非逻辑相机 ID 拍摄照片
- php - 带狮身人面像的智能过滤器
- javascript - 将保留按钮添加到表格的第 4 列。链接到灯箱/弹出窗口
- angular - 如何使用 Angular 6 中的一些 UI 即时编辑翻译文件?
- javascript - 如何在 ReactNative HighCharts 中设置 HTTP?
- javascript - 将图形点绘制为实时流:Highcharts
- encryption - 颤振:错误:类型“字符串”不是“加密”类型的“加密”类型的子类型
- javascript - 将 javascript 变量保存到文件中