Try to implement FirebaseInstanceIdService
to get refresh token.
Access the registration token:
You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken
in the context of onTokenRefresh
, and log the value as shown:
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
Full Code:
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
See my answer here.
EDITS:
You shouldn't be starting a FirebaseInstanceIdService yourself.
It will Called when the system determines that the tokens need to be refreshed. The application should call getToken() and send the tokens to all application servers.
This will not be called very frequently, it is needed for key rotation and to handle Instance ID changes due to:
The system will throttle the refresh event across all devices to avoid overloading application servers with token updates.
Try below way:
you'd call FirebaseInstanceID.getToken() anywhere off your main thread (whether it is a service, AsyncTask, etc), store the returned token locally and send it to your server. Then whenever
onTokenRefresh()
is called, you'd call FirebaseInstanceID.getToken() again, get a new token, and send that up to the server (probably including the old token as well so your server can remove it, replacing it with the new one).