In my MainActivity
in my log, I can see the token using FirebaseInstanceId.getInstance().getToken()
and it display the generated token. But it seems like in my MyFirebaseInstanceIDService
where it is extends to FirebaseInstanceIdService
, the onTokenRefresh()
is not called, where in this function it was said that the token is initially generated here. I needed to call sendRegistrationToServer()
that's why I'm trying to know why it doesn't go in the onTokenRefresh()
.
Here is my code
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
}
onTokenRefresh in FirebaseInstanceIdService is only called when a new token is generated. If your app was previously installed and generated a token then onTokenRefresh would not be called. Try uninstalling and reinstalling the app to force the generation of a new token, this would cause onTokenRefresh to be called.
Also be sure that your FirebaseInstanceIdService is properly defined in your AndroidManifest.xml
In your Manifest File.
<service
android:name="com.bnt.etailers.fcm.MyFireBaseInstanceIDService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name="com.bnt.etailers.fcm.GCMNotificationIntentService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
FirebaseInstanceIdService class
public class MyFireBaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFireBaseInstanceIDService.class.getSimpleName();
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
if (refreshedToken!=null) {
SettingPreferences.setStringValueInPref(this, SettingPreferences.REG_ID, 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.
}}
FirebaseMessagingService class.
public class GCMNotificationIntentService extends FirebaseMessagingService {
// Sets an ID for the notification, so it can be updated
public GCMNotificationIntentService() {
super();
}
@Override
public void onMessageReceived(RemoteMessage message) {
}}