我正在使用 FCM 向我的 Android 应用程序发送通知,该通知由我的 FirebaseMessagingService 接收和处理。效果很好。我从 FCM 通知中获取信息并将其传递给函数(在我的 FirebaseMessagingService 内)以创建意图。在“发送”到 MainActivity 页面之前,意图和附加内容包含从 FCM 收到的最新数据(到目前为止一切似乎都正常 - 功能如下):
const val channelId = "notification_channel"
const val channelName = "com.prod.myApp"
fun generateNotification(goToFragment: String, contact_id: String, source_origin: String){
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("fragmentToLoad", goToFragment)
intent.putExtra("contact_id", contact_id)
intent.putExtra("source_origin", source_origin)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE)
var builder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, channelId)
.setSmallIcon(R.drawable.ic_baseline_back_hand_24)
.setAutoCancel(true)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
notificationManager.notify(0, builder.build())
}
在 MainActivity 上接收意图并进行以下处理:
onNewIntent(intent) //NOTE: See below
if (intent.extras != null) {
if(intent.hasExtra("fragmentToLoad")){
when(intent.getStringExtra("fragmentToLoad").toString()){
"GetPic" -> {
myViewModel.setContactsOrigin(intent.getStringExtra("source_origin").toString())
myViewModel.setPostcardContactID(intent!!.getStringExtra("contact_id").toString())
supportFragmentManager.findFragmentById(R.id.myNavHostFragment) as NavHostFragment
val navController = navHostFragment.navController
navController.navigate(R.id.GetPic)
}
else -> {
Log.d("mainActivity","Intent option " + intent.hasExtra("fragmentToLoad").toString() + " is not an anticipated option")
}
}
}
这是 MainActivity 中的一个单独函数,但在 onCreate 之外:
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent) // Update the intent with new data
}
问题是 MainActivity 中的 getStringExtra("source_origin") 永远不会更新。它与第一次运行代码时提交的值相同(即使该值在 FirebaseMessagingService 中已更改多次)。例如,如果我第一次运行应用程序,FirebaseMessagingService 中的“source_origin”值设置为“banana”,则无论我在后续重新运行服务时将该值设置为什么,MainActivity 中意图中的值都将保留“香蕉”。我可以在 FirebaseMessagingService 中将其更改为“橙色”,当它到达 MainActivity 时,它仍然会显示为“香蕉”。
打开所请求片段的功能按预期工作。
这一切都发生在模拟器中。
我已经多次使缓存失效,包括重新启动 Android Studio。这对问题没有影响。
知道为什么这个错误不断发生吗?
我能够通过修改 PendingIntent.getActivity(context, requestCode,intent,flags) 中的 requestCode 值来解决这个问题,使其始终是唯一的 int 值。
文档指出: “由于这种行为,为了检索 PendingIntent,了解何时将两个 Intent 视为相同非常重要。人们常犯的错误是创建多个 PendingIntent 对象,其 Intent 仅在“额外”内容上有所不同,期望每次都能得到不同的 PendingIntent。这不会发生。”
此外,为了强制 PendingIntent 识别差异,我们可以执行以下操作: “...或提供给 #getActivity、#getActivities、getBroadcast 或 getService 的不同请求代码整数。”