FCM onMessageReceiver 没有被调用

FCM onMessageReceiver not getting called

我正在为聋人+盲人创建一个应用程序(他们可以看到屏幕上的颜色,但看不到细节)。我想让智能手表振动并在有人按门铃时显示某种颜色。门铃将通过节点通过 Firebase 通过节点向用户发送消息,请参见下面的示例:

import admin from 'firebase-admin';

// tslint:disable-next-line:no-var-requires
const serviceAccount = require('../../../firebase.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://example.firebaseio.com',
});

export function sendMessageToUser(
  token: string,
  payload: { data: { color: string; vibration: string; text: string } },
  priority: string,
) {
  const options = {
    priority,
    timeToLive: 60 * 60 * 24,
  };

  return new Promise((resolve, reject) => {
    admin
      .messaging()
      .sendToDevice(token, payload, options)
      .then(response => {
        console.log(response);
        resolve(response);
      })
      .catch(error => {
        console.log('error', error);
        reject(error);
      });
  });
}

智能手表通过以下服务接收 firebase 消息:

public class HapticsFirebaseMessagingService extends FirebaseMessagingService {

    private SharedPreferences sharedPreferences;

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

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);

        sharedPreferences.edit().putString("fb", token).apply();
    }

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

        Intent dialogIntent = new Intent(this, AlarmActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Bundle bundle = new Bundle();
        bundle.putString("color", color);
        bundle.putString("vibration", vibration);
        bundle.putString("text", text);
        dialogIntent.putExtras(bundle);
        startActivity(dialogIntent);
    }

    /**
     * Get the token from the shared preferences.
     */
    public static String getToken(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString("fb", "empty");
    }
}

当智能手表连接到电脑时,这工作正常,但当我断开智能手表与电脑的连接时,它会工作几分钟。但是几分钟后 onMessageReceived 没有被调用,也不会打开 activity。为什么 de service 不再接收消息?我该如何修复它,以便服务始终收到消息。消息总是需要尽快传递给用户,因为它被用作聋人+盲人的门铃。

如果你不想延迟,你必须将它添加到你的负载中 priority : 'high'。但请记住,这会增加设备的电池使用量等。

请访问此 page 了解更多信息。

经过一些测试,我让它工作了。这似乎是我使用的 npm 模块的问题。我用了Firebase admin which is given my the firebase documentation. It worked fine except that sending a message with the example above doesn't trigger the background service. In order to get this working properly i followed these

为了在应用程序通过节点在后台时触发 onmessageReceived,我使用了以下脚本:

function sendMessageToUser(
  token: string,
  data: { color: string; vibration: string; text: string },
  priority: string,
) {
  return new Promise((resolve, reject) => {
    fetch('https://fcm.googleapis.com/fcm/send', {
      method: 'POST',
      body: JSON.stringify({
        data,
        priority,
        to: token,
      }),
      headers: {
        'Content-type': 'application/json',
        Authorization: `key=${process.env.FIREBASE_API_KEY}`,
      },
    })
      .then(async (response: any) => {
        resolve(response);
      })
      .catch((exception: any) => {
        reject(exception);
      });
  });
}