我使用Firebase (FCM)向用户显示推送通知,我遇到了一个奇怪的问题。
我的代码适用于以下场景(使用FirebaseMessagingService):
这里是有趣的地方:
),这是很好的。
Intent mainIntent = getPackageManager().getLaunchIntentForPackage(getPackageName()); 
if (mainIntent != null) {
    mainIntent.addCategory(NOTIFICATION_CATEGORY);
    mainIntent.putExtra(.........);
}
PendingIntent pendingMainIntent = PendingIntent.getActivity(this, SERVICE_NOTIFICATION_ID, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, context.getString(R.string.default_notification_channel_id));
notificationBuilder.setContentIntent(pendingMainIntent);
//.....icon, color, pririty, autoCancel, setDefaults, setWhen, setShowWhen, contentText, setStyle
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
            getString(R.string.default_notification_channel_id),
            getString(R.string.default_notification_channel),
            NotificationManager.IMPORTANCE_HIGH
        );
        notificationManager.createNotificationChannel(channel);
        notificationBuilder.setChannelId(getString(R.string.default_notification_channel_id));
    }
    notificationManager.notify(SERVICE_NOTIFICATION_ID, notificationBuilder.build());
}如果有任何想法我会很感激。谢谢。
发布于 2020-09-15 12:03:16
当你第一次启动一个应用程序时,安卓会记住用来启动它的Intent。通常,当您从主屏幕启动应用程序时,这是一个包含ACTION=MAIN和CATEGORY=LAUNCHER的ACTION=MAIN。如果您的应用程序然后转到后台(无论出于什么原因),用户稍后点击主屏幕上的图标,就会使用相同的启动Intent。安卓将这与第一次启动应用程序的Intent相匹配,如果这些匹配,安卓不会启动新的Activity,它只会将包含应用程序的任务从后台带到前台,不管移动到后台时处于何种状态。在正常情况下,这正是您想要的行为(以及用户期望的行为)。
然而,当应用程序第一次从Notification上启动时,这可能会把事情搞砸。在你的情况下,这就是你所看到的。你从Notification启动应用程序,安卓会记住使用的Intent (从Notification),当你稍后启动应用程序时(同样是从Notification),安卓将Notification中的Intent与第一次启动应用程序的Intent相匹配,并认为您希望将现有的应用任务从后台带到前台。
根据你想要的行为,有几种方法可以解决这个问题。最好的做法可能是不要从Activity ( ACTION=MAIN和CATEGORY=LAUNCHER)中启动根Notification。相反,启动一个不同的Activity,让Activity决定下一步应该做什么(即:根据应用程序的状态,重定向到根Activity或其他什么东西)。您还应该在放置在NO_HISTORY中的Intent上设置Intent和Notification标志。这将确保安卓不会将这款Intent视为发布该应用程序的原因。
https://stackoverflow.com/questions/63880616
复制相似问题