How to get Android device token for push notifications?

Viewed 15482

We have been through various Stackoverflow questions and answers, and looked through documentation and articles but all the approaches we've tried such as FireBaseInstanceId and extending the FirebaseMessagingService all result in an empty token.

It is not clear how we get the token for the user's device, for push notification purposes.

Could someone please clarify how in 2021 we can get the user's device token?

Thanks

4 Answers

FireBaseInstanceId was deprecated and documentation say to use FirebaseMessaging for retrieve FCM token. In particular the method getToken() works in this way:

Returns the FCM registration token for this Firebase project. This creates a Firebase Installations ID, if one does not exist

So, in order to generate token, I don't think is mandatory to extends FirebaseMessagingService, just call it like so wherever you want

FirebaseMessaging.getInstance().token.addOnCompleteListener {
        if (!it.isSuccessful) {
            return@addOnCompleteListener
        }
        val token = it.result //this is the token retrieved
    }

Once you have a sample push notification project working, then the Java code is:

FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

Source= https://firebase.google.com/docs/cloud-messaging/android/client

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        Log.e("newToken", token);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

}

Add this in Android manifest file:

<service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>

Whenever your Application is installed first time and open, MyFirebaseMessagingService created and onNewToken(String token) method called and token generated which is your Device Token or FCM Token.

from this way you can get the unique device id

TelephonyManager telephonyManager;
telephonyManager = (TelephonyManager) getSystemService(Context.
                TELEPHONY_SERVICE);

getDeviceId() will returns the unique device ID.

String deviceId = telephonyManager.getDeviceId();

By the way this needs permission of android.permission.READ_PHONE_STATE

Related