FCM令牌何时过期?

72

FCM令牌何时过期?是在6个月后吗?

4个回答

122

不过它并不会过期。如果出现以下情况之一,它会自动更新:

根据https://firebase.google.com/docs/cloud-messaging/android/client

  1. - 应用删除实例ID
  2. - 应用在新设备上恢复
  3. - 用户卸载/重新安装应用
  4. - 用户清除应用数据。

监视令牌生成

每当生成新令牌时,onTokenRefresh回调都会触发,因此在其上下文中调用getToken可以确保您访问的是当前可用的注册令牌。请确保已将服务添加到您的清单中,然后在onTokenRefresh的上下文中调用getToken,并按如下所示记录该值:

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

编辑

onTokenRefresh()现在已经被弃用。应该使用onNewToken()代替。


20
服务器如何知道新令牌是用于新设备还是仅用于替换旧令牌? - Günter Zöchbauer
1
如果您在服务器端具有设备ID或用户ID字段,请与其进行比较并相应地进行更新。 - Hitesh Dhamshaniya
2
这非常有趣,考虑到令牌生成策略,这是有道理的,我们能获取源代码吗? - cutiko
1
@cutiko 我认为这就是链接。然而,我很难理解这个答案。在文档中写到,在这些情况下令牌会发生变化,但并没有解释原始令牌会发生什么! - Noah Martin
1
如果您将@NoahMartin存储在某个位置,然后尝试将其用作任何新FCM的目标,则它将不再有效。 - cutiko
此答案的源链接:https://firebase.google.com/docs/cloud-messaging/android/client#sample-register - Christopher Stephan

4
使用Firebase admin,您可以做到这一点:
async function isValidDeviceToken (deviceToken) {
  const {
    results: [notifResult]
  } = await firebaseAdmin.messaging().sendToDevice(
    deviceToken,
    {
      notification: {
        title: 'Device Registration',
        message: 'Your device has been registered.'
      }
    },
    {
      dryRun: true
    }
  );

  // returns true if valid, false if not.
  return !notifResult.error;
}

它的作用是检查提供的deviceToken是否有效。在幕后,Firebase管理员会检查deviceToken是否已注册。如果未注册,则会返回以下错误:
{
  error: FirebaseMessagingError: The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.
      at FirebaseMessagingError.FirebaseError [as constructor] (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:44:28)
      at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:90:28)
      at new FirebaseMessagingError (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:256:16)
      at Function.FirebaseMessagingError.fromServerError (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/utils/error.js:289:16)
      at /Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:105:63
      at Array.forEach (<anonymous>)
      at mapRawResponseToDevicesResponse (/Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:101:26)
      at /Users/aprilmintacpineda/projects/my-app/node_modules/firebase-admin/lib/messaging/messaging.js:370:24
      at processTicksAndRejections (node:internal/process/task_queues:94:5)
      at async isValidDeviceToken (/Users/aprilmintacpineda/projects/my-app/test.js:13:7) {
    errorInfo: {
      code: 'messaging/registration-token-not-registered',
      message: 'The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.'
    },
    codePrefix: 'messaging'
  }
}

2

如文档这里所述,令牌不会过期,只会在某些事件发生时更改。每当生成新令牌时,都会调用onTokenRefereshId方法。要实现此功能,请创建一个扩展FirebaseInstanceIdService的类,并重写onRefreshToken方法,如下所示:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }
}

不要忘记在清单文件中注册此服务。
<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

2
此意图动作现在被称为 com.google.firebase.MESSAGING_EVENT,请参见此处 - https://dev59.com/aqzka4cB1Zd3GeqP_Jrb - Vadim Kotov

0
如果应用程序超过1到2个月没有使用,它将变为“STALE”状态,因此订阅和刷新令牌的功能将停止。这不是一个固定的时间,但根据Firebase文档,建议检查来自FCM后端的无效令牌响应或最大注册时间为2个月之前。 参考:https://firebase.google.com/docs/cloud-messaging/manage-tokens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接