5 分钟后收到应用程序关闭时来自 Firebase 的仅数据消息

Data only message from Firebase when app is closed being received after 5 minutes

我试图在应用程序被用户关闭时在我的 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();
}

上面的代码在后台运行良好,我的意思是当应用程序只是 "minimized" 二级计划时。

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

正在从 Postman 发送消息:

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

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

问题:在后台运行后可能出现什么问题?为什么会发生这种行为?

经过深入搜索,我明白了。

我是 运行 华硕设备中的应用程序。根据此 Whosebug answer,ASUS 智能手机有一个性能技巧可以延长电池寿命,因此当您从最近使用的应用程序列表中滑动一个应用程序时,您是在 强制应用程序停止 。因此,负责接收消息的 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"

}