es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Ir a diferentes actividades cuando se haga clic en la notificación FCM.

Chicos, estoy usando FCM para enviar notificaciones a mi aplicación de Android, y funciona bien, pero cuando hago clic en la notificación me envía a una actividad específica que establecí aquí:

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, activity_togo_to.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "101")
            .setSmallIcon(R.drawable.ic_add)
            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody())
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Establecer la intención que se activará cuando el usuario toque la notificación
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    // notificationId es un entero único para cada notificación que debes definir
    notificationManager.notify(1, builder.build());
}

Mi problema es que no quiero ir a la misma actividad cuando se hace clic en una notificación.

Entonces, mi sistema de notificaciones funciona así:

Tengo dos tablas en la base de datos MySQL A y B:

Cuando se agrega una fila a la tabla A -> enviar notificación con el título: “hay un nuevo elemento A”

Cuando se agrega una fila a la tabla B -> enviar notificación con el título: “hay un nuevo elemento B”

Cuando hago clic en una notificación:

con el título: “hay un nuevo elemento A” -> ir a la actividad A

con el título: “hay un nuevo elemento B” -> ir a la actividad B

¿Cómo puedo lograr esto, chicos? Realmente lo necesito.

Agradezco cualquier ayuda.
Si no es posible, solo avísenme.

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para lograr esto, puedes agregar un campo adicional en la notificación push de FCM con el valor que indica qué actividad abrir cuando se haga clic en la notificación. Puedes usar diferentes valores para cada tipo de notificación, es decir, A y B.

    Aquí está el código modificado para lograr esto:

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        String notificationType = remoteMessage.getData().get("type");
    
        // Establecer la actividad a abrir según el tipo de notificación
        Class activityToGoTo = null;
        if(notificationType.equals("A")) {
            activityToGoTo = ActivityA.class;
        } else if(notificationType.equals("B")) {
            activityToGoTo = ActivityB.class;
        }
    
        Intent intent = new Intent(this, activityToGoTo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "101")
                .setSmallIcon(R.drawable.ic_add)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setContentText(remoteMessage.getNotification().getBody())
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                // Establecer el intent que se ejecutará cuando el usuario toque la notificación
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        // notificationId es un int único para cada notificación que debes definir
        notificationManager.notify(1, builder.build());
    }
    

    En el código anterior, estamos obteniendo el tipo de notificación de los datos del mensaje de FCM y estableciendo la variable activityToGoTo según el tipo. Luego, estamos pasando esta clase de actividad al constructor de Intent para abrir la actividad adecuada cuando se haga clic en la notificación.

    Finalmente, al enviar la notificación push desde el servidor, debes incluir el tipo de notificación en los datos del mensaje. Por ejemplo, puedes enviar el siguiente mensaje para un nuevo elemento en la tabla A:

    {
      "to": "DEVICE_TOKEN_HERE",
      "data": {
        "title": "Hay un nuevo elemento A",
        "body": "Echa un vistazo al nuevo elemento agregado a la tabla A",
        "type": "A"
      }
    }
    

    De manera similar, para un nuevo elemento en la tabla B, puedes enviar:

    {
      "to": "DEVICE_TOKEN_HERE",
      "data": {
        "title": "Hay un nuevo elemento B",
        "body": "Echa un vistazo al nuevo elemento agregado a la tabla B",
        "type": "B"
      }
    }
    

    Al hacer esto, cuando el usuario haga clic en la notificación, se abrirá la actividad adecuada según el tipo de notificación.

Comments are closed.