Getting GCM Registration ID using Firebase

2020-06-12 03:30发布

问题:

I have an ASP.net MVC server from where I want to send push notifications to my Android App. I have already implemented Firebase Messaging in the app and the notifications are working fine when sent from Firebase dashboard.

I have tried sending push notification using the server by sending a post request, but the request requires a to field. Earlier we used to send registration id provided by GCM there. Now since Firebase is handling it, how can I fetch the registration id to be put in the to field using Firebase SDK in Android?

回答1:

Hi and thanks for using Firebase Cloud Messaging!

You can fetch the registration-id calling:

FirebaseInstanceId.getInstance().getToken();

Differently from the GCM sdk, the new library automatically takes care of fetching the token as soon as possible, and then it caches it locally.

The above method will return the token, if available, or null if the fetching phase is still in progress.

You can use the callback onTokenRefresh() to be notified when the token is available or has been rotated.

public class InstanceIDService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToMyServer(refreshedToken);
    }
}

More info here: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register