Saltar al contenido

FirebaseInstanceIdService está obsoleto

Intenta interpretar el código bien antes de usarlo a tu proyecto si ttienes algo que aportar puedes dejarlo en los comentarios.

Solución:

Actualización 11-12-2020

Ahora FirebaseInstanceId también está desaprobado

Ahora necesitamos usar FirebaseInstallations.getInstance().getToken() y FirebaseMessaging.getInstance().token

CÓDIGO DE MUESTRA

FirebaseInstallations.getInstance().getToken(true).addOnCompleteListener 
            firebaseToken = it.result!!.token
        

        // OR
        FirebaseMessaging.getInstance().token.addOnCompleteListener 
            if(it.isComplete)
                firebaseToken = it.result.toString()
                Util.printLog(firebaseToken)
            
        

    

FirebaseInstanceIdService es obsoleto

DE DOCS: – Esta clase fue obsoleta. En favor de overriding onNewToken en FirebaseMessagingService. Una vez que se haya implementado, este servicio se puede eliminar de forma segura.

No es necesario usar FirebaseInstanceIdService servicio para obtener el token FCM Puede eliminar de forma segura FirebaseInstanceIdService Servicio

Ahora necesitamos @Override onNewToken obtener Token en FirebaseMessagingService

CÓDIGO DE MUESTRA

public class MyFirebaseMessagingService extends FirebaseMessagingService 

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

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) 

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

#EDITAR

Necesita registrar su FirebaseMessagingService en un archivo de manifiesto como este

    
        
            
            
        
    

#cómo conseguir token en tu actividad

.getToken(); también está en desuso si necesita obtener un token en su actividad que Use getInstanceId ()

Ahora necesitamos usar getInstanceId () para generar token

getInstanceId () Devuelve el ID y token generado automáticamente para esto Firebase proyecto.

Esto genera un ID de instancia si aún no existe, que comienza a enviar información periódicamente al backend de Firebase.

Devoluciones

  • Tarea que puede utilizar para ver el resultado a través de la InstanceIdResult que contiene el ID y token.

CÓDIGO DE MUESTRA

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

     
 );

## EDITAR 2

Aquí está el código de trabajo para 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())

    

firebaser aquí

Consulte la documentación de referencia para FirebaseInstanceIdService:

Esta clase fue obsoleta.

A favor de anular onNewToken en FirebaseMessagingService. Una vez que se haya implementado, este servicio se puede eliminar de forma segura.

Curiosamente el JavaDoc para FirebaseMessagingService no menciona el onNewToken método todavía. Parece que aún no se ha publicado toda la documentación actualizada. Presenté un problema interno para publicar las actualizaciones de los documentos de referencia y para actualizar también las muestras de la guía.

Mientras tanto, tanto las llamadas antiguas / obsoletas como las nuevas deberían funcionar. Si tiene problemas con alguno de ellos, publique el código y lo echaré un vistazo.

Y esto:

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

supongamos que es una solución de obsoleta:

FirebaseInstanceId.getInstance().getToken()

EDITAR

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

puede producir una excepción si la tarea aún no se ha completado, por lo que el método que describió Nilesh Rathod (con .addOnSuccessListener) es la forma correcta de hacerlo.

Kotlin:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this)  instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    

Te invitamos a añadir valor a nuestro contenido informacional participando con tu veteranía en las acotaciones.

¡Haz clic para puntuar esta entrada!
(Votos: 2 Promedio: 5)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *