Firebase onTokenRefresh() is not called

AndroidFirebaseFirebase Cloud-MessagingFirebase Notifications

Android Problem Overview


In my MainActivityin 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);
    }
}

Android Solutions


Solution 1 - Android

> 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) {

}}

Solution 2 - Android

I had the same problem like you. My mistake was the following: I placed my <service> tags outside the <application> tag in the AndroidManifest.xml file.

Now mine looks like this:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

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

And it works without any problem.

Solution 3 - Android

Yes this might happen some times.

Please call the following method wherever you want to get your fcm id.

    try {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d("Firbase id login", "Refreshed token: " + refreshedToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

Solution 4 - Android

Try re-install the app, by uninstall it first from your device or emulator. It will then generate a new token, thus onTokenRefresh() will be called again.

Solution 5 - Android

In my case I forgot to add internet permission in manifest,

<uses-permission android:name="android.permission.INTERNET" />

Hope most people won't make this mistake.

Solution 6 - Android

try {
    FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
    e.printStackTrace();
}

in onCreate method to delete token.

Solution 7 - Android

Reinstalling did the trick for me!

Solution 8 - Android

Make sure you have added

apply plugin: 'com.google.gms.google-services'

this to bottom of the app.gradle file

Solution 9 - Android

In my case, I tried everything but onTokenRefresh was never called. Then I change my WiFi and I connect to different network, Now it worked!!. Previous WiFi has good internet connectivity, Don't know why it was happening. May be this can help someone.

Solution 10 - Android

I have experienced that MyFirebaseInstanceIDService is not called when you are running your application on a device where internet connectivity is not available. In this way onTokenRefresh() is not called. So make sure that your device must has internet connection during running your application for taking updated FirebaseToken.

Also uninstall the previous app & Re-Install it for taking updated token. The registration token change when:

  1. The app deletes Instance ID

  2. The app is restored on a new device

  3. The user uninstalls/reinstall the app

  4. The user clears app data.

Solution 11 - Android

I've been struggling with that for over an hour, then I changed the following code and it suddenly worked.

handle your refreshedToken as such:

String refreshedToken;
    try {
        refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        Localytics.setPushRegistrationId(refreshedToken);
    } catch (Exception e) {
        Log.d(TAG, "Refreshed token, catch: " + e.toString());
        e.printStackTrace();
    }

Try adding android:exported="true"> to both MyFirebaseMessagingService and MyFirebaseInstanceIDService in manifest so it looks like that:

<service
        android:name="com.localytics.android.sample.fcm.MyFirebaseMessagingService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

    <service
        android:name="com.localytics.android.sample.fcm.MyFirebaseInstanceIDService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Uninstall your app, Install again, worked. Tested on real device.

android:exported="true" is a default option so you can also remove that entirely and it will be set to true.

Also if you want to call onTokenRefresh more explicitly, you can simply call that anywhere in your code:

String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Localytics.setPushRegistrationId(refreshedToken);

You don't have to rely on broadcast being received any more

Solution 12 - Android

There are several reasons to not calling the onTokenRefresh methon not called. I have listed that and mention it one by one .

  1. Please make sure you have added the internet permission

  2. check have you added the google-services.json file that generate from google console inside of app directory in your project

enter image description here

  1. In your module Gradle file (usually the app/build.gradle), add the apply plugin line at the bottom of the file to enable the Gradle plugin:

> apply plugin: 'com.android.application' >
> android { > // ... > } >
> dependencies { > // ... > implementation 'com.google.firebase:firebase-core:16.0.4' >
> // Getting a "Could not find" error? Make sure you have > // added the Google maven respository to your root build.gradle > } >
> // ADD THIS AT THE BOTTOM > apply plugin: 'com.google.gms.google-services'

  1. add the play service class path in project level build.gridle file

> buildscript { > // ... > dependencies { > // ... > classpath 'com.google.gms:google-services:4.1.0' // google-services plugin > } > } >
> allprojects { > // ... > repositories { > // ... > google() // Google's Maven repository > } > }

  1. Make sure you have added those service in the AndroidManifes file inside application tag

> android:allowBackup="true" > android:icon="@mipmap/ic_launcher" > android:label="@string/app_name" > android:supportsRtl="true" > android:theme="@style/AppTheme"> > > android:name=".MyFirebaseMessagingService"> > > > > > > android:name=".MyFirebaseInstanceIDService"> > > > > >

  1. onToken refresh is called when token refresh and when install the app for the first so make sure you have deleted the app manually or clear the data

  2. Make sure you have extends the FirebaseMessagingService in your service class

[Note : If its not working only for specific version for example android kitkat version then try to change the fcm version.]

Solution 13 - Android

I had the same problem. My device(kitkat 4.4.2) couldn't get onTokenRefresh() for some reason. My internet connection was perfect, google play services was up to date and all necessary contiditions for firebase to work were met. My code worked perfectly on the devices 5.0.0 and higher. To solve this issue i had to reset my device to factory settings and application started to work. I know it's tough measure but maybe it may help somebody. There must be some problems or conflict with other application, which caused onTokenRefresh() not to be called. Good luck!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnatsumiyuView Question on Stackoverflow
Solution 1 - AndroidSagar GangawaneView Answer on Stackoverflow
Solution 2 - AndroidviplezerView Answer on Stackoverflow
Solution 3 - AndroidSurendar DView Answer on Stackoverflow
Solution 4 - AndroidfarukView Answer on Stackoverflow
Solution 5 - AndroidSreedhu MadhuView Answer on Stackoverflow
Solution 6 - AndroidpruView Answer on Stackoverflow
Solution 7 - AndroidSterling DiazView Answer on Stackoverflow
Solution 8 - Androiduser2837615View Answer on Stackoverflow
Solution 9 - Androidkaranatwal.github.ioView Answer on Stackoverflow
Solution 10 - AndroidSheharyar EjazView Answer on Stackoverflow
Solution 11 - AndroiddanjarView Answer on Stackoverflow
Solution 12 - AndroidHoque MD ZahidulView Answer on Stackoverflow
Solution 13 - AndroidValiyor IrismetovView Answer on Stackoverflow