什么是 FCM 令牌在 Firebase?

在新的 Firebase 中,在 Notification 下,他们提到开发者可以向特定的设备发送通知。为此,它在控制台中请求 FCM 令牌。到底是什么,我怎么才能拿到那个信物?

191690 次浏览

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in . 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.


How can I get that token?

Update: The token can still be retrieved by calling getToken(), however, as per FCM's latest version, the FirebaseInstanceIdService.onTokenRefresh() has been replaced with FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


Old answer:

As per the 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.

Here is simple steps add this gradle:

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

No extra permission are needed in manifest like GCM. No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver is added automatically.

Migrate your listener service

A service extending InstanceIDListenerService is now required only if you want to access the FCM token.

This is needed if you want to

  • Manage device tokens to send a messages to single device directly, or Send messages to device group, or
  • Send messages to device group, or
  • Subscribe devices to topics with the server subscription management API.

Add Service in manifest

<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>

Change MyInstanceIDListenerService to extend FirebaseInstanceIdService, and update code to listen for token updates and get the token whenever a new token is generated.

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);
}


}

For more information visit

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

I have an update about "Firebase Cloud Messaging token" which I could get an information.

I really wanted to know about that change so just sent a mail to Support team. The Firebase Cloud Messaging token will get back to Server key soon again. There will be nothing to change. We can see Server key again after soon.

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

They deprecated getToken() method in the below release notes. Instead, we have to use 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
// ...
}
});

To handle success and failure in the same listener, attach an 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();
}
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, 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);
}