Android PendingIntent在从后台通知打开后无法启动活动

3

我正在使用Google FCM向我的应用程序发送通知。我目前正在发送数据通知,并让我的Android应用程序构造推送通知。我希望用户能够点击通知并将其路由到相应的片段/活动。

它的工作很好,除了一个问题。 用户终止应用程序 -> 接收通知 -> 点击通知 -> 应用程序启动并从通知传递数据正确到闪屏活动(我使用通知活动广播/启动意图) -> 用户在应用程序开启时接收到另一个通知 -> 用户点击通知 -> 刚刚正确启动的通知活动未能启动。

我正在想尽办法弄清楚可能出现的原因。我猜测这可能与上下文有关,因为应用是从通知中启动的,但我已经尝试过使用"this"和"getApplicationContext()",但都没有解决问题。

以下是我构建通知和待定意图的方法。

Intent notificationIntent = new Intent(this, NotificationActivity.class);
notificationIntent.putExtra(Variables.INTENT_NOTIFICATION_DATA, "dummy_data");
notificationIntent.setAction(Variables.NOTIFICATION_CLICK);
PendingIntent contentIntent = PendingIntent.getActivity(this,
        0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, Variables.CHANNEL)
        .setContentTitle("New Notification")
        .setContentText("Dummy text")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentIntent(contentIntent)
        .setAutoCancel(true)
        .setOngoing(false)
        .build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
    mNotificationManager.notify(0, notification);
}

当应用程序运行时,如果 NotificationActivity 无法正常工作,您是否在该活动中?如果是,请尝试覆盖 onNewIntent() 方法并查看其中的新意图详细信息,然后根据情况采取相应措施。 - Shark
你后来找到为什么会发生这种情况的解释了吗?或者为什么FLAG_CANCEL_CURRENT对你有用呢?我也遇到了同样的情况,但是这个标志并没有解决我的问题。 - Ameen Aliu
@AmeenAliu 抱歉已经有一段时间没有接触这方面的内容了,所以我对具体细节有些生疏。看着我的最终代码,我最终使用了CANCEL_CURRENT标志并将意图传递给我使用的主活动。在该活动的onNewIntent中,我获取意图的数据,然后进行相应的路由。我最终放弃了负责路由的单独NotificationActivity。 - Jesse R
嗯。谢谢@Jesse - Ameen Aliu
这个问题解决了吗?我遇到了这个问题,但还不知道如何解决。 - newbie
显示剩余4条评论
1个回答

0

我之前也遇到过同样的问题。我设法通过向意图添加一个随机字符串来解决它。

 val intent = Intent(this, SomeActivity::class.java).apply {
     action = Random.nextInt().toString()
 }

以您的示例为例,应该是这样的:

Intent notificationIntent = new Intent(this, NotificationActivity.class);
notificationIntent.putExtra(Variables.INTENT_NOTIFICATION_DATA, "dummy_data");
notificationIntent.setAction(String.valueOf(new Random().nextInt()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接