OnMessageRecieved 没有在后台应用程序中被解雇

OnMessageRecieved not getting fired in background app

我正在尝试重定向到点击不同通知时的不同分页。 OnMessagedRecieved 不会在应用程序 运行 在后台时仅在其在前台时被触发。

根据文档notification foreground, background触发的是系统托盘。

所以我查找了如何让它在后台运行,我发现了这个 tutorial

根据本教程:

As explained below, by using FCM console you can only send notification messages. notification messages can be handled by the onMessageReceived method in foregrounded application and deliver to the device’s system tray in backgrounded application. User taps on notification and default application launcher will be opened. if you want to handle notification in every state of application you must use data message and onMessageReceived method.

所以我查了一下数据消息到底是什么,通知消息是什么。 Documentation

我遵循了教程,但它对我不起作用。 这是我的代码:

public async Task<bool> WakeUp(string[] tokens)
    {
        var message = new Message()
        {
            RegistrationID= tokens,
            Notification = new Notification()
            {
                Title = "testing",
                Body = "test"
            },
            Android = new AndroidConfig()
            {
                Notification = new AndroidNotification()
                {
                    Color = "#FF0000",
                    ClickAction = "MyActivity"
                }
            },
            Data = new Dictionary<string, string>()
            {
                {
                    "notificationType", NotificationType.WakeUp.ToString()
                }
            }
        };

        return await SendAsyncMessage(message).ConfigureAwait(false);
    }


public async Task<bool> SendAsyncMessage(Message message)
    {
        var jsonMessage = JsonConvert.SerializeObject(message);
        var request = new HttpRequestMessage(HttpMethod, FIREBASE_PUSH_NOTIFICATION_URL)
        {
            Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json")
        };
        request.Headers.TryAddWithoutValidation("Authorization", $"key={ConfigurationManager.AppSettings["FirebaseNotificationServerKey"]}");
        request.Headers.TryAddWithoutValidation("Sender", $"id={ConfigurationManager.AppSettings["FirebaseNotificationSenderID"]}");
        HttpResponseMessage result;
        using (var client = new HttpClient())
        {
            result = await client.SendAsync(request).ConfigureAwait(false);
        }

        return result.IsSuccessStatusCode;
    }

这就是我在我的应用程序中接收代码的方式

public override void OnMessageReceived(RemoteMessage message)
    {
       Console.WriteLine("message recieved");
    }

原始 Json

{
"registration_ids":["myToken"],
"condition":null,
"data":
{
    "notificationType":"WakeUp"
},
"notification":
{
    "title":"testing",
    "body":"test",
    "image":null
},
"android":
{
    "collapse_key":null,
    "restricted_package_name":null,
    "data":null,
    "notification":
    {
        "title":null,
        "body":null,
        "icon":null,
        "color":"#FF0000",
        "sound":null,
        "tag":null,
        "image":null,
        "click_action":"mActivity",
        "title_loc_key":null,
        "title_loc_args":null,
        "body_loc_key":null,
        "body_loc_args":null,
        "channel_id":null
    },
    "fcm_options":null,
    "priority":"high",
    "ttl":null
},
"webpush":null,
"apns":null,
"fcm_options":null,
"topic":null

}

已收到通知,但未触发 OnMessageRecieved。我认为通知中心是负责显示通知的人。

可能是什么问题?

1。为什么会这样?

FCM (Firebase Cloud Messaging) 中有两种类型的消息:

  1. 显示消息:只有当您的应用处于前台
  2. 时,这些消息才会触发onMessageReceived()回调
  3. 数据消息:这些消息会触发 onMessageReceived() 回调 even 如果您的应用在 foreground/background/killed

NOTE: Firebase team have not developed a UI to send data-messages to your devices, yet. You should use your server for sending this type!



2。如何?

为此,您必须向以下 URL:

执行 POST 请求

POST https://fcm.googleapis.com/fcm/send

Headers

  • 键: Content-Type值: application/json
  • 键: Authorization值: key=<your-server-key>

Body 使用主题

{
    "to": "/topics/my_topic",
    "data": {
        "my_custom_key": "my_custom_value",
        "my_custom_key2": true
     }
}

或者如果您想将其发送到特定设备

{
    "data": {
        "my_custom_key": "my_custom_value",
        "my_custom_key2": true
     },
    "registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
}


NOTE: Be sure you're not adding JSON key notification
NOTE: To get your server key, you can find it in the firebase console: Your project -> settings -> Project settings -> Cloud messaging -> Server Key

3。如何处理推送消息?

这是您处理收到的消息的方式:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) { 
     Map<String, String> data = remoteMessage.getData();
     String myCustomKey = data.get("my_custom_key");

     // Manage data
}

这是参考here