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.
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:
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 deIntent
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:
De manera similar, para un nuevo elemento en la tabla B, puedes enviar:
Al hacer esto, cuando el usuario haga clic en la notificación, se abrirá la actividad adecuada según el tipo de notificación.