How to get Android Device Token in Kotlin for Firebase Cloud Messaging

Issue

I’m trying to save the Device Token for an Android device and use it with Firebase Cloud Messaging, but I’m having a problem, and I think I’m getting an incorrect token.

When I try to request the Device Token from an Android device, I use the following function:

    FirebaseInstallations.getInstance().id.addOnCompleteListener { task: Task<String?> ->
        if (task.isSuccessful) {
            val token = task.result

            if (token != null && userID != null) {
                Log.d("token ---->>", token)

            }

        }

However, when I get the token, it’s super short, almost like it’s being cut off. This is an example: fEOC4mBXRguYo4ur1v-fs_

I’ve comparing it to the device ID’s I would get on iOS devices. I also tried to use the token to receive notifications, but it wouldn’t work.

On iOS, the device id was generated by th device, and not Firebase, which is what the function above seems to be doing.

What am I doing wrong?

Solution

FirebaseInstallations isn’t the correct token for FCM! I had to use FirebaseMessaging and use the following:

FirebaseMessaging.getInstance().token
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    Log.w(TAG, "Fetching FCM registration token failed", task.exception)
                    return@OnCompleteListener
                }

                val token = task.result
                
                Log.d(TAG, token)
           
            })

Answered By – Meers E. Chahine

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *