点击通知栏,如果应用程序在后台,则不会在活动中收到消息



我正在按照本教程在我的应用中实现 Firebase推送通知功能。

但我发现了一件事,如果应用程序在foreground,那么只有我在 Toast 和 TextView 中收到(显示(消息

另一方面,如果应用程序在点击background,我也不会收到要在文本视图和 Toast 中显示的消息

而我想在两种情况下(Either App is in Foreground or Background)Toast 和 TextView 中显示消息

注意:我正在从 Firebase 控制台本身推送消息。

可能吗?

MyFirebaseMessagingService.java

private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
}else{
// If the app is in background, firebase itself handles the notification
}
}

主要活动.java

mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
displayFirebaseRegId();
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
txtMessage.setText(message);
}
}
};

FCM 有两种类型的消息:通知和数据。如果您希望 FCM 代表客户端应用处理显示通知,请使用通知消息。如果要在客户端应用上处理消息,请使用数据消息。

下面是示例,

{
"to": “token ID”,
"notification": {
//params
},
"data": {
//params
}
}

有效负载与消息类型时的行为,

通知消息

  1. 前台 - 消息已接收已触发
  2. 后台 - 通知显示在系统托盘上并由 FCM 处理
  3. 应用未运行 - 通知显示在系统托盘上并由 FCM 处理

数据消息

  1. 前台 - 消息已接收
  2. 背景 - 在消息已接收
  3. 应用未运行 - 消息已接收

通知和数据

  1. 前台 - 消息已接收
  2. 背景 - 托盘中的通知和数据有效负载将通过点击意图的附加内容进行处理
  3. 应用未运行 - 托盘中的通知和数据有效负载将通过点击意图的额外内容进行处理。

希望对您有所帮助!

最新更新