将 Firebase 云消息发送到已关闭的应用程序不起作用

Sending Firebase Cloud Message to closed App does not work

我正在尝试使用 Firebase 云消息传递进行一些操作,我已经到了可以使用 FCM 控制台通过 FCM 令牌向设备发送消息的地步。我认为即使您的应用未完全 运行,您也可以收到这些消息。但是当我的应用程序在后台 运行 时,我只能收到这些消息。

我现在的问题是,当您的应用不是 运行 时是否可以接收消息?如果可以,我该如何实现?

这是我添加到清单中的内容:

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/app_icon" />

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />


    <service
        android:name=".MyFirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

并在 类 中:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    //if the message contains data payload
    //It is a map of custom keyvalues
    //we can read it easily
    if(remoteMessage.getData().size() > 0){
        //handle the data message here
    }

    //getting the title and the body
    String title = remoteMessage.getNotification().getTitle();
    String body = remoteMessage.getNotification().getBody();
}
}


public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService{
//private Socket mSocket;

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();

    String token = FirebaseInstanceId.getInstance().getToken();

    Log.d("MyRefreshedToken", token);

    storeToken(token);
}

private void storeToken(String token) {
    SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
}

是的,当您的应用不是 运行 时,可以使用您的 onMessageReceived-method 接收消息。为此,您需要发送一条数据消息,也称为静默推送消息。这意味着您需要省略通知标题和 body 属性,并且只发送包含数据 属性.

的信息

例如

{
  "message": {
    "token":"78yadsbjbasjkdjbkasbdjkbak...",
    "data": {
      "Topic" : "Data message",
      "Content" : "This message should be handled by onMessageReceived regardless if the app is running or not.",
    }
  }
}

有关更多信息,请查看 Firebase 文档中的以下页面: