我正在关注 this在我的应用程序中实现 Firebase 推送通知 功能的教程。
但我发现一件事,如果应用程序在前台
,那么只有我在 Toast 和 TextView 中获取(显示)消息。
另一方面,如果应用程序在后台
中,我也不会没有收到消息以显示在 TextView 和 Toast 中。
而我想在两种情况下在 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
}
}
MainActivity.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
}
}
当负载带有消息类型时的行为,
通知消息
- 前台 - onMessageReceived 触发
- 背景 - 通知显示在系统托盘上并由 FCM 处理
- 应用未运行 - 通知显示在系统托盘上并由 FCM 处理
数据消息
- 前台 - onMessageReceived
- 背景 - onMessageReceived
- 应用未运行 - onMessageReceived
通知和数据
- 前台 - onMessageReceived
- 背景 - 托盘中的通知和数据负载将通过额外的 intent on tap 处理
- 应用未运行 - 托盘中的通知和数据有效负载将通过额外的 intent on tap 处理。
希望对您有所帮助!
关于android - 如果应用程序在后台,则点击通知栏不会在 Activity 中收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45452746/