【问题标题】:Override intent extras覆盖意图附加功能
【发布时间】:2016-12-23 10:37:43
【问题描述】:

我正在使用以下代码 (Kotlin) 创建通知

val builder = NotificationCompat.Builder(ctx)
           ........
      .setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent<MainActivity>()
            .putExtra("id", member.id)
            .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))

因此,当点击通知时,MainActivity 将选择通知到达的用户。

override fun onNewIntent(intent: Intent?) {
    val id = intent?.getStringExtra("id") ?: return
    selectUser(extra)
}

我正在发送来自 2 个不同用户的 2 个通知。单击第一个通知后,它可以正常工作(id==_User1UUID)并选择用户。然后我按回,从第二个用户发送另一个通知,点击它,意图仍然包含以前的用户 ID 并选择它(通过断点检查)。

我知道,这是因为FLAG_ACTIVITY_REORDER_TO_FRONT,但我必须只保留MainActivity 的一个实例。

【问题讨论】:

  • 将 'android:launchMode="singleTask"' 属性放入 AndroidManifest 文件中的活动中。
  • @keyur9779 我已经在清单中有这个,但这个标志不是也需要吗?
  • @keyur9779 尝试删除 FLAG_ACTIVITY_REORDER_TO_FRONT,但仍然只创建了一个实例并正常工作,谢谢

标签: android android-intent android-pendingintent


【解决方案1】:

您可能遇到的问题是您没有生成唯一的PendingIntents。如果您有 2 个针对不同用户的通知,他们将使用相同的 PendingIntent,因此您会在两者中看到相同的 id

要创建唯一的PendingIntents,请更改以下内容:

 .setContentIntent(PendingIntent.getActivity(ctx, 891, ctx.newIntent<MainActivity>()
        .putExtra("id", member.id)
        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))

到这里:

int randomNumber = ... // Use some random number here, or use your "id" if your "id" can be converted to an integer here.
                       //  This random number needs to be unique for each Notification you create.

 .setContentIntent(PendingIntent.getActivity(ctx, randomNumber, ctx.newIntent<MainActivity>()
        .putExtra("id", member.id)
        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), u))

【讨论】:

    【解决方案2】:

    您实际上需要给定的代码来使每个通知都独一无二

    notificationManager.notify( (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
    

    如果你已经这样做了,那么试试下面给出的代码

    Intent intent = new Intent(this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                            PendingIntent.FLAG_ONE_SHOT);
    

    【讨论】:

    • 我刚刚删除了FLAG_ACTIVITY_REORDER_TO_FRONT 它有效,但感谢您的帮助
    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多