首页 > 解决方案 > 5 分钟后收到应用关闭时来自 Firebase 的仅数据消息

问题描述

当应用程序被用户关闭时,我试图在我的 Android 托盘上显示一条数据消息,即当用户将应用程序拖到最近应用程序列表的一侧时。虽然,数据消息只是像这样被接收:

  1. 应用程序已关闭。已发送数据消息。
  2. 关闭应用程序时未收到消息。
  3. 应用程序已打开。
  4. 4~5 分钟后收到数据消息并显示在 Android 托盘中。

为了实现这一点,我正在使用react-native-firebase库,遵循其docs

import firebase from 'react-native-firebase';
import type { RemoteMessage } from 'react-native-firebase';

export default async (message: RemoteMessage) => {

    const notifPromise = new Promise((resolve, reject) => {

         let notification = new firebase.notifications.Notification();
              notification.android.setPriority(firebase.notifications.Android.Priority.High);
              notification.android.setChannelId("test-channel");

        resolve(firebase.notifications().displayNotification(notification));
    }); 

    console.log("MESSAGE IN BACKGROUND OR APP CLOSED");

    return notifPromise.resolve();
}

上面的代码在后台运行良好,我的意思是当应用程序只是“最小化”到辅助计划时。

AndroidManifest.xml、HeadlessTask 和 MainApllication.java 理论上是符合文档的。我只是在 Android 托盘中显示空白 UI 进行测试。

邮递员发送的消息:

{
"to": "erVxmCT6rgA:APA91bGn6q9...",

"data": {
    "custom1": "custom1",
    "custom2": "custom2"
   }
}

问题:一旦它在后台运行会出现什么问题?为什么会发生这种行为?

标签: react-nativefirebase-cloud-messagingreact-native-firebase

解决方案


经过深入搜索,我可以弄清楚。

我在华硕设备上运行应用程序。根据这个stackoverflow的回答,华硕智能手机有一个性能技巧可以延长电池寿命,所以当你从最近的应用程序列表中刷掉一个应用程序时,你是在强制应用程序停止。因此,负责接收消息的 HeadlessJSTask 取自 android 进程列表。

我还在我的代码中进行了一些编辑:

修复承诺:

export default async (message: RemoteMessage) => {

    const notification = new firebase.notifications.Notification();
              notification.android.setPriority(firebase.notifications.Android.Priority.High);
              notification.android.setChannelId("test-channel");
              notification.setTitle(message.data.custom1);

        firebase.notifications().displayNotification(notification);

    return Promise.resolve(message);
}

在我们的数据消息中设置高优先级(后台和应用关闭消息是必需的):

{

"to": "cKUNOaOnvaY:APA91bFVAPLSuHogmZfxc1GlhqOhEkxcscoRvZxRrzno0XjyDkqYZVmNqJVL4v6mcQgH4p9zt9Zxz5aDugCjNy7CBg_pbXb8u8X6336K0x6WffdXoGOl50lCtHt46oS78Yyc9XM3gPJQ",

"data": {
    "custom1": "custom1",
    "custom2": "custom2"
},

"priority": "high"

}

推荐阅读