roostaamir
roostaamir

Reputation: 1968

how to access firebase device token from outside of `onRefreshToken` in android

I want to access the firebase generated token from within an activity and inside a function I have like this:

private void getFirebaseDeviceToken() {
    //get firebase token
}

I know I can get this token within onRefreshToken and when the token changes or a brand new token is generated, but my app requires that I access this token outside this service and in my activity when a special event has occurred.

I have no idea how to do this and I will be grateful if anyone can help me

Upvotes: 0

Views: 784

Answers (4)

nir
nir

Reputation: 312

FirebaseInstanceId.getInstance().getToken(); -> the getToken method is deprecated.

you should use:

FirebaseInstanceId.getInstance().getInstanceId() 

1.this returns a Task callback on which you can add a listener:

    FirebaseInstanceId.getInstance().getInstanceId()
    .addOnSuccessListener(this, //activity context
        instanceIdResult -> {instanceIdResult.getToken()
                             //do what you what with the token here  
                             });

}

*you should pass the Activity context so the listener will unregister when the activity finishes.

By the way onRefreshToken() is also deprecated. you should now use onNewToken in FcmMessagingService check out the docs

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

From anywhere in your app, you can get the token with:

FirebaseInstanceId.getInstance().getToken(); 

If you store the token on some other system too (such as in SharedPreferences or in the Firebase Database), be sure to also handle onTokenRefresh() so that your secondary system always has the latest token.

Upvotes: 1

Chintan Soni
Chintan Soni

Reputation: 25267

What I did was, I just saved it in SharedPreferences with my util as below:

private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    SharedPreferenceUtils.getInstance(this).setValue(getString(R.string.firebase_cloud_messaging_token), token);
}

And whenever I want to get that token, i wrote a method for that too:

public String getDeviceToken() {
    return SharedPreferenceUtils
            .getInstance(this)
            .getStringValue(getString(R.string.firebase_cloud_messaging_token), "").equals("")
            ? FirebaseInstanceId.getInstance().getToken()
            : SharedPreferenceUtils.getInstance(this).getStringValue(getString(R.string.firebase_cloud_messaging_token), "");
}

Upvotes: 0

Tanishq Sharma
Tanishq Sharma

Reputation: 538

One way round will be to store the token in SharedPreferences whenever a new token is generated.

And you can retrieve that token from your custom method.

It would be more appropriate if we could understand the functionality and need for this method.

Upvotes: 0

Related Questions