【发布时间】:2020-09-14 08:21:27
【问题描述】:
我正在使用 Firebase (FCM) 向用户显示推送通知,但遇到了一个奇怪的问题。
我的代码适用于以下场景(使用 FirebaseMessagingService):
- 前台应用 - 在 onReceive() 中接收数据并在应用内显示一个弹出窗口。
- 后台应用程序 - 在 onReceive() 中接收数据并向用户显示通知。如果单击此按钮,应用程序将被带回前面。 在 LauncherActivity 中接收到此意图,然后调用 finish() 将我带到我已经打开的任何活动。
- 应用程序完全关闭 - 与背景相同。应用将被启动,并且 Intent 将在 LauncherActivity 中处理,然后再调用 finish()。
这就是有趣的地方:
- 应用程序完全关闭 -> 通过通知打开它(在 LauncherActivity 中收到意图) -> 将应用程序置于后台并发送另一个通知 -> 当单击此通知时,LauncherActivity 将被完全忽略(不再调用 onCreate),我直接参加我已经进行的任何活动。这里的意图没有额外内容或类别。 为什么在这种特定情况下会绕过 LauncherActivity?请记住,如果应用最初是正常启动的(而不是通过点击通知),这可以正常工作
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());
}
我会很感激任何想法。谢谢。
【问题讨论】:
标签: java android android-notifications android-pendingintent launch