使用 PendingIntent 传递数据并在应用启动时使用 onNewIntent 检索

问题描述

我有一个 Android 应用程序,它将接收推送通知。该通知具有可穿戴设备支持,因此该通知也将在带有操作按钮的 Android Wear 中可见。

我希望在通知到达 onMessageReceived 类中的 FirebaseMessagingService 时传递数据。尝试在 Intent 中设置数据并通过 Pending Intent 传递。

val intent = Intent(this,MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.data = Uri.parse("12345")
        intent.putExtra("user_id","USER ID")
        intent.putExtra("date","DATE")
        val pendingIntent = PendingIntent.getActivity(
            applicationContext,System.currentTimeMillis().toInt(),intent,0
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel =
                NotificationChannel(CHANNEL_ID,CHANNEL_NAME,CHANNEL_IMPORTANCE)
            val notificationmanager =
                this.getSystemService(Context.NOTIFICATION_SERVICE) as notificationmanager
            notificationmanager.createNotificationChannel(notificationChannel)

            val notificationBuilder =  NotificationCompat.Builder(this,CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(body)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .extend(NotificationCompat.WearableExtender()
                    .addAction(NotificationCompat.Action(R.drawable.icon,"Explore",pendingIntent))
                )
            notificationmanager.notify(0,notificationBuilder.build())
        }

当点击来自 Wear 的通知时,在 onNewIntent 中捕获意图以获取传递的数据。但是找不到传递过来的数据。

override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    setIntent(intent)
    // intent.getStringExtra("date")
    // intent.extras.getString("date")
    // intent.extras.get("date")
    // intent.data
}

无法获取数据。有没有办法让待定的意图通过意图?或者如何获取通过 Pending Intent 传递的值。

解决方法

我的假设是没有调用 onNewIntent()

如果您指定 FLAG_ACTIVITY_CLEAR_TOP 并且您的应用程序已经在运行并且任务堆栈中有 MainActivity 的实例,Android 将移除 MainActivity 的现有实例并创建一个新实例.带有“extras”的 Intent 将在 onCreate() 中传递,onNewIntent() 将不会被调用。

如果您的应用没有运行,点击通知将启动您的应用并创建一个新的 MainActivity 实例,带有“extras”的 Intent 将在 onCreate()onNewIntent() 不会被调用。

此外,由于您放入 IntentPendingIntent 将被 Android 用于从非 Activity 上下文启动 Activity,因此您需要指定Intent.FLAG_ACTIVITY_NEW_TASK

此外,在获取带有“extras”的 FLAG_UPDATE_CURRENT 时,您应该始终指定 PendingIntent,因为如果不这样做,您可能会得到带有一些旧“extras”的现有 PendingIntent 或也许根本没有。使用 FLAG_UPDATE_CURRENT 将确保您的 Intent “额外内容”被复制到 PendingIntent 中,即使它已经存在。像这样:

val intent = Intent(this,MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_CLEAR_TOP)
    intent.data = Uri.parse("12345")
    intent.putExtra("user_id","USER ID")
    intent.putExtra("date","DATE")

val pendingIntent = PendingIntent.getActivity(
        applicationContext,System.currentTimeMillis().toInt(),intent,PendingIntent.FLAG_UPDATE_CURRENT
    )