No se llama a Firebase onTokenRefresh()


En mi MainActivity en mi registro, puedo ver el token usando FirebaseInstanceId.getInstance().getToken() y muestra el token generado. Pero parece que en mi MyFirebaseInstanceIDService donde se extiende a FirebaseInstanceIdService, el onTokenRefresh() no es llamado, donde en esta función se dijo que el token generado inicialmente, aquí. Necesitaba llamar a sendRegistrationToServer() es por eso que estoy tratando de saber por qué no va en el onTokenRefresh().

Aquí está mi código

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);
    }
}
Author: natsumiyu, 2016-05-26

12 answers

OnTokenRefresh en FirebaseInstanceIdService solo se llama cuando se genera un nuevo token. Si su aplicación se instaló previamente y generó un token, no se llamaría a onTokenRefresh. Intente desinstalar y reinstalar la aplicación para forzar la generación de un nuevo token, esto causaría que se llame a onTokenRefresh.

También asegúrese de que su FirebaseInstanceIdService esté correctamente definido en su AndroidManifest.xml

En tu Manifiesto 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.
}}

Clase FirebaseMessagingService.

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

}}
 93
Author: Sagar Gangawane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-09 06:46:54

Tenía el mismo problema que tú. Mi error fue el siguiente: Coloqué mis etiquetas <service> fuera de la etiqueta <application> en el AndroidManifest.archivo xml.

Ahora el mío se ve así:

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

Y funciona sin ningún problema.

 21
Author: viplezer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-26 13:28:58

Intente volver a instalar la aplicación, desinstalándola primero de su dispositivo o emulador. Luego generará un nuevo token, por lo que onTokenRefresh() será llamado de nuevo.

 12
Author: faruk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-29 07:27:27

Sí, esto puede suceder algunas veces.

Por favor llame al siguiente método donde quiera obtener su fcm id.

    try {
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d("Firbase id login", "Refreshed token: " + refreshedToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
 11
Author: Surendar D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-09 05:56:46

En mi caso me olvidé de añadir el permiso de Internet en el manifiesto,

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

Espero que la mayoría de la gente no cometa este error.

 11
Author: Sreedhu Madhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-25 10:15:46
try {
    FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
    e.printStackTrace();
}

En onCreate método para eliminar token.

 2
Author: pru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-22 08:18:48

Asegúrese de haber añadido

Aplicar plugin: 'com.Google.gms.google-servicios'

Esto al final de la aplicación.gradle file

 2
Author: user2837615,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-12 12:06:13

En mi caso, lo intenté todo pero onTokenRefresh nunca me llamaron. Luego cambio mi WiFi y me conecto a diferentes red, Ahora funcionó!!. Anterior WiFi tiene buena conectividad a Internet, no sé por qué estaba sucediendo. Puede ser que esto pueda ayudar a alguien.

 1
Author: karanatwal.github.io,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-01 13:35:19

Reinstalar hizo el truco para mí!

 1
Author: Sterling Diaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 17:52:49

He experimentado que MyFirebaseInstanceIDService no se llama cuando está ejecutando su aplicación en un dispositivo donde la conectividad a Internet no está disponible. De esta manera no se llama a onTokenRefresh (). Así que asegúrese de que su dispositivo debe tener conexión a Internet durante la ejecución de su aplicación para tomar FirebaseToken actualizado.

También desinstale la aplicación anterior y Vuelva a instalarla para tomar el token actualizado. El token de registro cambia cuando:

1) La aplicación elimina el ID de instancia

2) La aplicación se restaura en un nuevo dispositivo

3) El usuario desinstala/reinstala la aplicación

4) El usuario borra los datos de la aplicación.

 0
Author: Sheharyar Ejaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 08:36:05

He estado luchando con eso durante más de una hora, luego cambié el siguiente código y de repente funcionó.

Maneja tu refreshedToken como tal:

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();
    }

Intenta agregar android: exported= "true" > tanto a MyFirebaseMessagingService como a MyFirebaseInstanceIDService en manifest para que se vea así:

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

Desinstalar la aplicación, Instalar de nuevo, trabajado. Probado en dispositivo real.

Android: exported = "true" es una opción predeterminada por lo que también puede eliminar por completo y se ajustará a la verdad.

Además, si desea llamar a onTokenRefresh de manera más explícita, simplemente puede llamar a eso en cualquier lugar de su código:

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

Ya no tienes que confiar en que la transmisión se reciba

 0
Author: danjar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 16:54:16

Yo tenía el mismo problema. Mi dispositivo(kitkat 4.4.2) no pudo obtener onTokenRefresh () por alguna razón. Mi conexión a Internet era perfecta, los servicios de Google Play estaban actualizados y se cumplieron todos los requisitos necesarios para que firebase funcionara. Mi código funcionó perfectamente en los dispositivos 5.0.0 y superiores. Para resolver este problema tuve que restablecer mi dispositivo a la configuración de fábrica y la aplicación comenzó a funcionar. Sé que es una medida difícil, pero tal vez pueda ayudar a alguien. Debe haber algunos problemas o conflictos con otra aplicación, que causó que no se llamara a onTokenRefresh (). ¡Buena suerte!

 0
Author: Valiyor Irismetov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 13:28:18