Firebase 中的 FCM 令牌是什么?

What is FCM token in Firebase?

在新的 Firebase 中,在通知下,他们提到开发人员可以向特定设备发送通知。为此,它会在控制台中请求 FCM 令牌。它到底是什么以及我如何获得该令牌?

具体是什么?

一个 FCM 令牌,或者通常称为 registrationToken,如 . As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.


我怎样才能得到那个令牌?

更新:仍然可以通过调用 getToken() 来检索令牌,但是,根据 FCM 的最新版本,FirebaseInstanceIdService.onTokenRefresh() 已替换为 FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


旧答案:

根据 FCM docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

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

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

这是简单的步骤 添加此 gradle:

dependencies {
  compile "com.google.firebase:firebase-messaging:9.0.0"
}

清单中不需要像 GCM 那样的额外权限。 不需要像 GCM 这样的接收器来显示。使用 FCM,会自动添加 com.google.android.gms.gcm.GcmReceiver

迁移您的侦听器服务

现在仅当您想访问 FCM 令牌时才需要扩展 InstanceIDListenerService 的服务。

如果你想的话,这是必需的

  • 管理设备令牌以直接向单个设备发送消息,或者 向设备组发送消息,或
  • 向设备组发送消息,或
  • 使用服务器订阅管理为设备订阅主题API。

在清单中添加服务

<service
    android:name=".MyInstanceIDListenerService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
    </intent-filter>
</service>

<service
    android:name=".MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

更改 MyInstanceIDListenerService 以扩展 FirebaseInstanceIdService,并更新代码以侦听令牌更新并在生成新令牌时获取令牌。

public class MyInstanceIDListenerService extends FirebaseInstanceIdService {

  ...

  /**
   * Called if InstanceID token is updated. This may occur if the security of
   * the previous token had been compromised. Note that this is also called
   * when the InstanceID token is initially generated, so this is where
   * you retrieve the token.
   */
  // [START refresh_token]
  @Override
  public void onTokenRefresh() {
      // Get updated InstanceID token.
      String refreshedToken = FirebaseInstanceId.getInstance().getToken();
      Log.d(TAG, "Refreshed token: " + refreshedToken);
      // TODO: Implement this method to send any registration to your app's servers.
      sendRegistrationToServer(refreshedToken);
  }

}

有关详细信息,请访问

  1. How to import former GCM Projects into Firebase
  2. How to access the token
  3. How to set up firebase

我有关于 "Firebase Cloud Messaging token" 的更新,我可以获取信息。

我真的很想知道这个变化,所以刚刚给支持团队发了一封邮件。 Firebase 云消息传递令牌将很快再次返回到服务器密钥。没有什么可以改变的。很快我们就可以再次看到服务器密钥了。

FirebaseInstanceIdService 现已弃用。您应该在 FirebaseMessagingService 的 onNewToken 方法中获取令牌。

Check out the docs

他们在以下发行说明中弃用了 getToken() 方法。相反,我们必须使用 getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

要在同一个侦听器中处理成功和失败,请附加一个 OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

此外,FirebaseInstanceIdService Class 已被弃用,他们在 FireBaseMessagingService 中提出了 onNewToken 方法来替代 onTokenRefresh,

你可以在这里参考发行说明, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}