【问题标题】:PendingIntent.FLAG_UPDATE_CURRENT recreates ActivityPendingIntent.FLAG_UPDATE_CURRENT 重新创建活动
【发布时间】:2019-09-21 02:40:43
【问题描述】:

我有一个通知,当我点击它时,如果它仍未运行,我想启动应用程序,但如果应用程序已经运行,我不想重新启动它。 所以,我在创建PendingIntent 时使用了PendingIntent.FLAG_UPDATE_CURRENT 标志。

我的代码:

private val notificationManager by lazy { NotificationManagerCompat.from(this) }

fun testPush() {
        val notificationBuilder = NotificationCompat.Builder(this, BuildConfig.APPLICATION_ID)
                .setSmallIcon(R.drawable.ill_launcher)

        notificationBuilder
                .setContentTitle("Title")
                .setContentText("Test text")
                .setContentIntent(buildPendingIntent())

        notificationBuilder
                .setAutoCancel(true)
                .priority = NotificationCompat.PRIORITY_DEFAULT

        notificationManager.notify(1, notificationBuilder.build())
}

 private fun buildPendingIntent(): PendingIntent {

        val intent = Intent(this, RootActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        intent.putExtra("action", RootActivity.DEFAULT_INTENT)

        return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

但是当我启动应用程序并单击通知时,会重新创建活动。

【问题讨论】:

  • FLAG_UPDATE_CURRENT 没有这种效果。这表示您想要更新Intent 的附加功能,如果已经有一个PendingIntent 对应的Intent。它没有说明您是否要重用现有的活动实例。
  • @CommonsWare 所以,我需要为Intent 设置一些标志来获得描述的效果,对吧?在这里:intent.flags = Intent.<SOME_FLAG>。文档说,Intent.FLAG_ACTIVITY_SINGLE_TOP 将以所描述的方式工作:“如果活动已经在历史堆栈的顶部运行,则不会启动它”。但是我的应用程序不是这样工作的。
  • 默认情况下,您将完成一个新任务,因为PendingIntent 是从您的任务现有活动之一以外的其他活动中调用的。 IIRC,您需要在清单中的 <activity> 元素中调整一些与任务相关的属性。
  • @CommonsWare 你能提供例子吗?你是说android:launchMode属性之类的东西吗?
  • 我没有这个方便的样品,抱歉。

标签: android android-intent push-notification android-notifications android-pendingintent


【解决方案1】:

您需要为您的应用程序创建一个“启动Intent”,而不是像您那样为RootActivity 构建Intent。最简单的方法是调用PackageManager.getLaunchIntentForPackage() 并传递您自己的包名。在对PendingIntent.getActivity() 的调用中使用返回的Intent

如果您的应用没有运行,这将启动它,否则,如果它已经在运行,它只会将包含您的应用的现有任务带到前台。

【讨论】:

  • 它仍然会重新创建活动
  • 难以置信。请编辑您的问题并发布您的清单以及您用于创建PendingIntent 的代码。另外你怎么知道Activity 被重新创建了?
  • 试试安卓6、7
猜你喜欢
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
相关资源
最近更新 更多