FirebaseMessagingService
的方法onMessageReceived()
我们应该override
来处理notifications
,但这只适用于应用程序位于Foreground
的情况。
要处理notifications
即使应用处于后台,我也会覆盖handleIntent
,只需拨打onMessageReceived()
。
在FirebaseMessagingService
11.6.0中,方法handleIntent
成为最终方法,据说,我无法像我一样覆盖它。
当我的应用程序在11.6.0中处于后台时,我该如何处理通知?
public class NotificationsListenerService extends FirebaseMessagingService {
private static final String TAG = "NotificationsListenerService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage)
String notifyData = remoteMessage.getData().get("notifData");
if(notifyData.contains("|")){
String[] itens = notifyData.split("\\|");
notifyData = itens[0];
}
String notifyType = remoteMessage.getData().get("notifType");
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body");
if(!isAppInForeground(App.getContext())){
sendNotification(title, message, notifyData, notifyType);
}
}
@Override
public final void handleIntent(Intent intent) {
...
this.onMessageReceived(builder.build());
...
}
private void sendNotification(String messageTitle, String messageBody, String notifyData, String notifyType) {
...
}
//Detect if app is in foreground
private boolean isAppInForeground(Context context) {
...
}
}
答案 0 :(得分:3)
任何人都无意覆盖handleIntent()
。这就是为什么它成为最终的原因。此外,您会注意到javadocs完全没有 - 这是故意的。
如果要在任何情况下(前景和背景)处理消息,请使用onMessageReceived()。该方法的javadoc表示:
收到邮件时被叫。
当收到通知消息时,这是也 应用程序在前台。可以检索通知参数 使用getNotification()。
这应该适用于数据消息,但不适用于从控制台发送的通知消息。通知消息具有不同的传递行为。请参阅有关message types和how to handle them。
的文档答案 1 :(得分:3)
我在FirebaseMessagingService 11.8.0文档中添加了它,在https://firebase.google.com/docs/cloud-messaging/android/receive中声明如果通知有数据有效负载,当应用程序在前台时,它将调用onMessageRecieved(),如果应用程序在后台,通知和数据有效负载在启动器Activity的意图的附加内容中传递。
因此,这意味着您需要决定如何在两个地方处理通知,具体取决于用户是在积极使用该应用还是在后台。
如您所见,如果您在应用程序位于前台时收到通知,则会调用onMessageReceived()并在那里处理通知。
当应用程序从后台启动时,您有两个选项:
1:默认情况下,通知会发送到您的系统托盘,单击它时会打开您的主要活动,将数据(onMessageReceived()中的remoteMessage.getData())传递给您的活动意图额外。您可以像这样处理主要活动中的额外内容并决定如何处理它们,例如检查键值并启动相关意图。
// [START handle_data_extras]
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
我还建议您查看firebase消息传递示例应用,了解相关提示:https://github.com/firebase/quickstart-android/tree/master/messaging
答案 2 :(得分:1)
我在更新firebase库版本后遇到了同样的问题。
我认为最简单的方法是再次降级firebase库(我使用11.4.2),handleIntent()
仍然有效!