Firebase 消息在后台

Firebase-messaging in background

我知道这个问题太老了,上面有很多答案,但我还没有找到我的决定。

我想用 firebase-cloud-messaging 更新小部件,但是 Firebase 方法 onMessageReceived() 在应用程序处于后台时未调用。

我试过像这里的大多数答案一样更改对数据的通知,但这对我没有帮助:onMessageReceived() 当应用程序甚至在 foreground.

所以,我的 Firebase JSON 是:

{ "registration_ids": [ "ids" ], 
"priority": "high", 
"content_available": true, 
"data": {
    "id_request": "1229",
    "unreadedAnnouncements": "4",
    "requestsCount": "9",
    "survaysCount": "5", 
    "sound":"default", 
    "title":"test", 
    "message": "test", 
    "body": "test" } }

如果重要,我的 Firebase 依赖项:

implementation 'com.google.firebase:firebase-core:10.2.1'
implementation 'com.google.firebase:firebase-messaging:10.2.1'
implementation 'com.google.firebase:firebase-auth:10.2.1'

也许有一些新的解决方案? SO 上有 2016 年以来最多的解决方案。

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

    if (remoteMessage.getData() != null)
        sendNotification(remoteMessage);
}

然后你可以这样解析数据:

    private void sendNotification(RemoteMessage remoteMessage)
    {
       Map<String, String> data = remoteMessage.getData();
       String title = data.get("title");
       String content = data.get("content");
       // your code
    }

帮助我的解决方案: 在 Firebase 中,我刚刚将字段 registration_ids 更改为 to.

最终 Firebase JSON:

{ "to": [ "ids" ], 
"priority": "high", 
"content_available": true, 
"data": {
    "id_request": "1229",
    "unreadedAnnouncements": "4",
    "requestsCount": "9",
    "survaysCount": "5", 
    "sound":"default", 
    "title":"test", 
    "message": "test", 
    "body": "test" } }