【问题标题】:subsequent notifications does not reload the Main Activity后续通知不会重新加载 Main Activity
【发布时间】:2020-03-24 20:39:24
【问题描述】:

我的应用程序创建一个通知,当用户点击通知时,它会打开包含一些 EXTRA 数据的 Main Activity。

当用户手动打开应用程序或第一次弹出通知时,一切正常。

但问题是,当App第一次被通知打开时,后续通知并没有重新加载Main Activity。如果应用程序被隐藏,它只会显示它(无需重新加载)。

这就是我创建通知的方式


fun createNotification(title: String, message: String, intent: Intent?) {
        val mBuilder = NotificationCompat.Builder(
            context,
            NOTIFICATION_CHANNEL_ID
        )
        mBuilder.setSmallIcon(R.drawable.notification_ico)
        mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

        if (intent != null) {
            Log.e(TAG, "Intent dey")
            val resultPendingIntent = PendingIntent.getActivity(
                context,
                0 /* Request code */,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            mBuilder.setContentIntent(resultPendingIntent)
        } else {
            Log.e(TAG, "Unavailable dey")
        }

        val mNotificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "Enterprise Advantage",
                importance
            )
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            notificationChannel.enableVibration(true)
            notificationChannel.vibrationPattern =
                longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID)
            mNotificationManager.createNotificationChannel(notificationChannel)
        }
        mNotificationManager.notify(0 /* Request Code */, mBuilder.build())
    }

【问题讨论】:

标签: android kotlin android-intent android-notifications android-pendingintent


【解决方案1】:

好的,来自@Rahul Shukla 的评论,

我在意图上设置了一个动作

val intent = Intent(this, MainActivity::class.java)
intent.action = System.currentTimeMillis().toString()

然后将待处理意图的Flag更改为PendingIntent.FLAG_ONE_SHOT

val resultPendingIntent = PendingIntent.getActivity(
                context,
                0 /* Request code */,
                intent,
                PendingIntent.FLAG_ONE_SHOT
            )

【讨论】:

  • 一般来说,我不会使用FLAG_ONE_SHOT。这有很多讨厌的副作用,而且没有必要。如果您设置了一个唯一的 ACTION(您正在执行此操作),那么您将获得唯一的 PendingIntents(这是您需要的)而没有标志。请参阅stackoverflow.com/questions/29778294/… 了解更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 2017-03-15
  • 1970-01-01
相关资源
最近更新 更多