如果应用程序被卸载,Firebase 从数据库中删除相关行

nuh*_*oca 2 android firebase firebase-cloud-messaging google-cloud-firestore

我正在使用 Cloud Firestore 来保存应用程序令牌以发送推送通知。但是,当用户卸载并重新安装应用程序时,Firestore 会收到同一用户的不同令牌。当用户卸载应用程序时,如何删除上一个令牌的相关行?

提前致谢。

Fra*_*len 8

通常,您需要检测令牌何时失效,并在那时将其删除。例如,当令牌被循环使用时(用户安装应用程序时每隔几周就会发生一次),您将希望利用这一时刻从数据库中删除旧令牌并添加新令牌。这样做可以最大限度地减少数据库中过时令牌的数量。

所以在步骤中意味着onTokenRefresh()

  1. 检查本地存储中是否有令牌(例如共享首选项)。如果是这样,请从数据库和本地存储中删除该令牌。

  2. 将新令牌存储在数据库和本地存储中。

但是在您的情况下这是不可能的,因为onTokenRefresh在卸载应用程序时不会调用它,并且在重新安装它时您将不知道以前的令牌。

处理以这种方式和其他方式留下的过时令牌的最简单方法是在发送到该令牌失败时删除它们。使用 Cloud Functions 发送 FCM 通知示例有一个很好的例子:

admin
  .messaging()
  .sendToDevice(tokens, payload)
  .then((response) => {
    // For each message check if there was an error.
    const tokensToRemove = [];
    response.results.forEach((result, index) => {
      const error = result.error;
      if (error) {
        console.error('Failure sending notification to', tokens[index], error);
        // Cleanup the tokens who are not registered anymore.
        if (error.code === 'messaging/invalid-registration-token' ||
            error.code === 'messaging/registration-token-not-registered') {
          tokensSnapshot.ref.child(tokens[index]).remove();
        }
      }
    });
  });
Run Code Online (Sandbox Code Playgroud)