FirebaseInstanceIdService est déprécié

Espère que tous vous au courant de cette classe, utilisé pour recevoir des avis de jeton à chaque fois que firebase notification jeton obtenu rafraîchi nous obtenir le jeton d'actualisation à partir de cette classe, à Partir de la méthode suivante.

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}

pour utiliser ceci comme je veux implémenter FCM, j'ai étendu MyClass de FirebaseInstanceIdService

mais, montrant que FirebaseInstanceIdService est déprécié

quelqu'un le sait?, Quelle méthode ou la classe que je devrais utiliser à la place de ceci pour obtenir le token rafraîchi puisque ceci est déprécié.

j'utilise: implementation 'com.google.firebase:firebase-messaging:17.1.0'

j'ai vérifié le document pour même il n'y a rien mentionné à ce sujet. : FCM SETUP DOCUMENT


mise à jour

cette question a été corrigée.

Comme Google déprécié le FirebaseInstanceService ,

j'ai posé la question pour trouver le chemin et j'arrive à savoir que nous pouvons obtenir le jeton de FirebaseMessagingService ,

comme auparavant, lorsque j'ai posé la question Documents n'ont pas été mis à jour, mais maintenant Google docs mis à jour afin de plus amples informations, se référer à ce google doc: FirebaseMessagingService

ancien de: FirebaseInstanceService (Déprécié)

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}

nouveau de: FirebaseMessagingService

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.d("NEW_TOKEN",s);
}

Merci.

76
demandé sur Uttam Panchasara 2018-07-01 15:12:40

4 réponses

firebaser ici

vérifier la documentation de référence pour FirebaseInstanceIdService :

cette classe a été dépréciée.

en faveur de onNewToken dans FirebaseMessagingService . Une fois que ce service a été mis en œuvre, il peut être retiré en toute sécurité.

bizarrement, le JavaDoc pour FirebaseMessagingService ne mentionne pas onNewToken méthode encore. Il semble que tous les documents mis à jour n'aient pas encore été publiés. J'ai déposé un numéro interne pour obtenir les mises à jour des docs de référence publiés, et pour obtenir les échantillons dans le guide mis à jour aussi.

entre-temps, les anciens appels et les nouveaux devraient fonctionner. Si vous avez des problèmes avec l'un ou l'autre, postez le code et je regarderai.

55
répondu Frank van Puffelen 2018-07-03 00:38:18

Oui FirebaseInstanceIdService est déprécié

de DOCS: - cette classe a été dépréciée. En faveur de overriding onNewToken dans FirebaseMessagingService . Une fois que ce service a été mis en œuvre, il peut être retiré en toute sécurité.

pas besoin d'utiliser FirebaseInstanceIdService service pour obtenir un jeton FCM vous pouvez retirer en toute sécurité FirebaseInstanceIdService service

maintenant nous avons besoin de @Override onNewToken obtenir Token dans FirebaseMessagingService

CODE ÉCHANTILLON

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        Log.e("NEW_TOKEN", s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        Log.e("JSON_OBJECT", object.toString());

        String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";

        long pattern[] = {0, 1000, 500, 1000};

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
                    NotificationManager.IMPORTANCE_HIGH);

            notificationChannel.setDescription("");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(pattern);
            notificationChannel.enableVibration(true);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            channel.canBypassDnd();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage.getNotification().getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true);


        mNotificationManager.notify(1000, notificationBuilder.build());
    }
}

MODIFIER

vous devez enregistrer votre FirebaseMessagingService dans un fichier manifeste comme celui-ci

    <service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>

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

comment obtenir token en votre activité

.getToken(); est également déprécié si vous avez besoin d'obtenir token dans votre activité que D'utiliser getInstanceId ()

maintenant nous devons utiliser getInstanceId () pour générer un token

getInstanceId () retourne le ID et généré automatiquement un token pour ce projet Firebase .

génère un identifiant D'Instance s'il n'existe pas encore, qui commence à envoyer périodiquement des informations à la base de données Firebase backend.

Renvoie

  • Tâche que vous pouvez utiliser pour voir le résultat via le InstanceIdResult qui tient le ID et token .

CODE ÉCHANTILLON

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String newToken = instanceIdResult.getToken();
           Log.e("newToken",newToken);

     }
 });

EDIT 2

voici le code de travail pour kotlin

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onNewToken(p0: String?) {

    }

    override fun onMessageReceived(remoteMessage: RemoteMessage?) {


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val NOTIFICATION_CHANNEL_ID = "Nilesh_channel"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH)

            notificationChannel.description = "Description"
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
            notificationChannel.enableVibration(true)
            notificationManager.createNotificationChannel(notificationChannel)
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
            channel.canBypassDnd()
        }

        val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage!!.getNotification()!!.getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true)


        notificationManager.notify(1000, notificationBuilder.build())

    }
}
70
répondu Nilesh Rathod 2018-08-14 05:39:20

et ceci:

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()

suppose être une solution de dépréciée:

FirebaseInstanceId.getInstance().getToken()

MODIFIER

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken() peut produire exception si la tâche n'est pas encore terminée, de sorte que la méthode sorcière Nilesh Rathod décrit (avec .addOnSuccessListener ) est la bonne façon de le faire.

Kotlin:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    }
6
répondu Aleksandar Mironov 2018-07-10 09:08:22

Propre Réponse

à Partir de FirebaseInstanceIdService de la documentation.

FirebaseInstanceIdService

cette classe a été dépréciée. En faveur d'une prépondérance de la nouveauté dans FirebaseMessagingService. Une fois que ce service a été mis en œuvre, il peut être retiré en toute sécurité.

Changements à mettre en œuvre :

  1. supprimer le service FirebaseInstanceIdService , comme ils l'ont fusionné dans FirebaseMessagingService .
  2. Remplacer onNewToken() FirebaseMessagingService .

utilisez votre ancien FirebaseMessagingService . et annulez onNewToken comme ci-dessous.

public class FCMService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String s) {
        Log.d("FCM_TOKEN", s);
        // save in SharedPreference for future use
    }
}
  1. pour obtenir token à l'exécution, vous peut utiliser FirebaseInstanceId.getInstance().getInstanceId()

exemple

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String token = instanceIdResult.getToken();
           Log.d("FCM_TOKEN",token);
     }
 });

C'est tout, oui!

4
répondu Khemraj 2018-08-31 18:18:40