How can I get device id for push notifications using firebase in android

Ahsan Malik picture Ahsan Malik · Jun 19, 2017 · Viewed 33k times · Source

I found this solution and I think it is not the ID which is required for notification kindly tell me by some samples:

import android.provider.Settings.Secure;

private String androidIdd = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

I guess I don't need an android id. I just want to get the device unique ID for Firebase Notification or GCM.

Answer

StefMa picture StefMa · Jun 19, 2017

Instead of using some third party tutorials I would prefer to take a look into the official Firebase Cloud Messaging documentation.

If you have set up everything correctly you can just scroll to the topic

Retrieve the current registration token

When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken(). This method returns null if the token has not yet been generated.

In a nutshell: Call FirebaseInstanceId.getInstance().getToken() to reveive the current device token.

EDIT:

The command FirebaseInstanceId.getInstance().getToken() is deprecated. The same documentation mentions a new approach as below:

FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

            }
        });