khalid karam khalid karam - 1 month ago 29
Android Question

Run FirebaseInstanceIdService only after authentication

FirebaseInstanceIdService starts at the beginning of the app, I want it to generate the token only after an authentication.

I tried this line in MainActivity (it lunched after authentication) but it didn't work :

startService(new Intent(this, FirebaseInstanceIDService.class));


This is my service's declaration :

<service android:name=".services.FirebaseInstanceIDService" >
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>


Thanks.

Answer

You will always get instance ID before auth. You can

1) Save it to shared preferences in onTokenRefresh(), and then process it after auth

2) Get it after auth manually.

In both cases code will be the same

FirebaseInstanceId.getInstance().getToken()

And it's working everywhere, because of singleton underneath. Just don't forget to check, that it's not null in case of unexpected error, that should never happen. (At least, it never happened for me)

This token will be the same before and after auth, but may change over time. There are, how I handle it

if (FirebaseAuth.getInstance().getCurrentUser()!=null) {
    processToken(FirebaseInstanceId.getInstance().getToken())
}

And after auth: just processToken(FirebaseInstanceId.getInstance().getToken())

That's all