检查 Firebase 注册令牌是否无效

时间:2020-12-28 14:25:15

标签: android firebase firebase-cloud-messaging

我有一个应用,用户可以在其中通过 Firebase 注册/登录。一个用户可以有多个设备,在这些设备之间共享他的所有数据(当然他必须登录)。我通过 Firebase 设备令牌跟踪所有设备,并在用户更新特定设备上的某些内容时发送适当的更新通知

现在我知道 firebase 令牌正在刷新,但我怎么知道令牌无效?假设用户有 4 台设备,他使用一个帐户登录。现在他删除了其中一个上的应用程序,然后重新安装,因此他获得了一个新令牌。这意味着现在我的服务器上有 5 个设备令牌,但仍然只有 4 个设备。最好的方法是将令牌绑定到一些不可更改的设备 ID,如 MAC 或 IMEI,但由于隐私政策是不可能的。 是否有其他方法可以将已被撤销/失效的令牌捞出?

1 个答案:

答案 0 :(得分:1)

检测过期/撤销的 FCM 令牌的常用方法是在发送消息期间。届时 FCM 会准确告诉您哪些令牌已过期,然后您可以将它们从数据库中删除。

有关此示例,请参阅 functions-samples repo 中的此 Node.js 代码:

<块引用>
 tokens = Object.keys(tokensSnapshot.val());
 // Send notifications to all tokens.
 const response = await admin.messaging().sendToDevice(tokens, payload);
 // 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') {
       tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
     }
   }
 });
 return Promise.all(tokensToRemove);
相关问题