我发现有关此主题的firebase文档太难以捉摸:https://firebase.google.com/docs/cloud-messaging/android/receive#backgrounded
我听过这个回答:https://stackoverflow.com/a/47392189/2068732and 当应用程序处于后台时,我能够收到通知。
但是,由于不推荐使用WakefulBroadcastReceiver类,因此不能令人满意。
将通知转发到MyFirebaseMessagingService的onMessageReceived()方法的正确方法是什么?
这是我的MyFirebaseMessagingService类:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(getClass().getName(), "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(getClass().getName(), "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(getClass().getName(), "Message Notification Body: " + remoteMessage.getNotification().getBody());
displayNotification(remoteMessage);
}
}
}
和清单:
<service
android:name=".firebase.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
答案 0 :(得分:0)
只有在有效负载remoteMessage.getNotification() != null
中有通知数据时才会成立。
如果您有数据有效负载,则displayNotification()
应位于if块
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(getClass().getName(), "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(getClass().getName(), "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(getClass().getName(), "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
displayNotification(remoteMessage);
}
}
答案 1 :(得分:0)
请添加以下权限。
<uses-permission android:name="android.permission.WAKE_LOCK" />
有关详细信息,请查看this
答案 2 :(得分:0)