Reputation: 765
As we know we can get firebase token
on onNewToken(...)
in our class inherited of FirebaseMessagingService
. But I have a question, that method will not call on update app case, and if I already have a token before, but I didn't save it. How to get it??
Example: In my class inherit from FirebaseMessagingService
class CustomFirebaseService : FirebaseMessagingService() {
override fun onNewToken(newToken: String) {
supper.onNewToken(newToken)
// I have token in here, but I already didn't save it on any where (sharedperf, db,..)
}
And now in my application, I need to use it, but I don't sure what the best way to get it??
class App: Application() {
override fun onCreate() {
super.onCreate()
// I need to use token here, but method onNewToken will not called, because the current token is valid.
}
}
Maybe, Can I use FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(..)
? Do it duplicate with my custom service??
Upvotes: 1
Views: 806
Reputation: 599946
As the Firebase documentation on getting the current registration token says:
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(); // 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(); } });
You typically only need this in development, as the initial token is typically generated before you have an onNewToken
. Once your app is in production, the onNewToken
code will be called from the moment the first token is generated.
Upvotes: 1