在 Android 12 中,点击通知时系统不再触发 onNewIntent() 方法,因此无法通过该方法获取数据负载。解决方法是在 Notification 的 pending intent 中指定一个自定义 action,并在 activity 的 onNewIntent() 方法中针对该 action 进行处理。
示例代码:
val notificationIntent = Intent(context, YourActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
action = "your_custom_action"
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, channelId)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(R.drawable.ic_notification)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null && intent.action == "your_custom_action") {
val dataPayload = intent.getStringExtra("data_payload")
// 处理数据负载
}
}
在处理通知点击事件的业务逻辑中发送包含自定义 action 的 pending intent ,确保使用与 action 相同的 PendingIntent.FLAG_UPDATE_CURRENT 标志位。在 activity 的 onNewIntent() 方法中判断 intent 是否为 null,并通过 action 获取数据负载。