Firebase (FCM): activa la actividad y pasa los datos al hacer clic en la notificación. androide
Debe haber una implementación clara de cómo trabajar con la notificación y los datos de Firebase. He leído muchas respuestas pero no puedo hacer que funcione. Aquí están mis pasos:
1.) Estoy pasando notificación y datos a android en PHP y parece estar bien:
- Cómo quitar la notificación de la barra de notificación mediante programación en android?
- Problemas con Android Bluetooth LE Notificaciones
- ¿Cómo puedo ocultar una actividad?
- ¿Cómo mostrar iconos diferentes para la barra de estado y la barra de notificación en Android?
- ¿Cómo agregar una insignia de notificación / cuenta al icono de la aplicación en los dispositivos Sony Xperia?
$msg = array ( "body" => $body, "title" => $title, "sound" => "mySound" ); $data = array ( "user_id" => $res_id, "date" => $date, "hal_id" => $hal_id, "M_view" => $M_view ); $fields = array ( 'registration_ids' => $registrationIds, 'notification' => $msg, 'data' => $data ); $headers = array ( 'Authorization: key='.API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch );
2.) cuando la notificación y los datos se reciben en Android muestra notificación. Cuando hago clic en esta notificación se abre la aplicación. Pero no puedo encontrar la manera de manejar los datos cuando se abre la aplicación. Hay diferencias de pareja cuando la aplicación está en primer plano y backround. El código que tengo ahora es el siguiente:
public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { String user_id = "0"; String date = "0"; String cal_id = "0"; String M_view = "0"; if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); user_id = remoteMessage.getData().get("user_id"); date = remoteMessage.getData().get("date"); hal_id = remoteMessage.getData().get("hal_id"); M_view = remoteMessage.getData().get("M_view"); } //Calling method to generate notification sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view); } private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("fcm_notification", "Y"); intent.putExtra("user_id", user_id); intent.putExtra("date", date); intent.putExtra("hal_id", hal_id); intent.putExtra("M_view", M_view); int uniqueInt = (int) (System.currentTimeMillis() & 0xff); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent, PendingIntent.FLAG_UPDATE_CURRENT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setSmallIcon(R.drawable.ic_launcher) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); }}
3.) Cuando utilizo el código de arriba y cuando hago clic en la notificación todo lo que hace se abre la aplicación si en el fondo. Si la aplicación en primer plano, luego en la notificación haga clic en simplemente descarta la notificación. Sin embargo, quiero recibir datos y abrir Actividad específica en ambos escenarios (fondo y primer plano). Tengo en MainActivity el siguiente código, pero no puedo obtener datos. Fcm_notification, date, hal_id devuelve null.
public class MainActivity extends Activity { UserFunctions userFunctions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); Intent intent_o = getIntent(); } @Override protected void onResume() { super.onResume(); userFunctions = new UserFunctions(); if(userFunctions.isUserLoggedIn(getApplicationContext())){ Intent intent_o = getIntent(); String fcm_notification = intent_o.getStringExtra("fcm_notification") ; String user_id = intent_o.getStringExtra("user_id"); String date = intent_o.getStringExtra("date"); String hal_id = intent_o.getStringExtra("hal_id"); String M_view = intent_o.getStringExtra("M_view"); Intent intent = new Intent(this, JobList.class); // THIS RETURNS NULL, user_id = null System.out.print("FCM" + user_id); startActivity(intent); finish(); }else{ // user is not logged in show login screen Intent login = new Intent(this, LoginActivity.class); startActivity(login); // Closing dashboard screen finish(); } }}
SI cualquier persona puede dirigir o consejo cómo puedo recuperar datos en MainActivity.java de Firebase en cualquier escenario (primero plano o fondo) que sería fantástico.
- Android: no se pueden mostrar varias líneas de texto en la notificación
- Gestionar notificaciones múltiples / apilar notificaciones desde GCM
- Android 4.1: ¿Cómo comprobar las notificaciones están deshabilitadas para la aplicación?
- Android: Notificaciones push de GCM que no aparecen en la lista de notificaciones
- Notificaciones push iOS y código nativo cliente-cliente de Android
- ¿Es posible configurar la notificación ampliada como predeterminada en las notificaciones de texto grande?
- ¿Debería llamar a WakeLock antes de crear una notificación?
- Cómo crear una notificación personalizada en android
Así que primero fuera, voy a poner en los detalles mencionados en el manejo de mensajes Documentos .
En el resumen de la fila Ambos , se muestra que cuando la aplicación está en primer plano , la carga útil se tratará en su onMessageReceived()
.
Para abrir la actividad desde onMessageReceived()
, debe comprobar si los datos que necesita están en la carga, si lo hace, llame a su actividad específica y luego pasar todos los demás detalles que necesita a través de la intención.
Ahora, si la aplicación está en segundo plano , se menciona en los documentos que la notificación es recibida por la bandeja del sistema de Android y que la carga de data
se puede recuperar de los extras de la intención.
Sólo añadiendo en los detalles de mi respuesta aquí, que prácticamente sólo da la declaración docs y un enlace a una muestra:
Manejar mensajes de notificación en una aplicación en segundo plano
Cuando su aplicación está en segundo plano, Android dirige los mensajes de notificación a la bandeja del sistema. Un usuario pulsa en la notificación abre el lanzador de aplicaciones de forma predeterminada.
Esto incluye mensajes que contienen tanto la notificación como la carga de datos (y todos los mensajes enviados desde la consola Notificaciones). En estos casos, la notificación se entrega a la bandeja del sistema del dispositivo y la carga útil de datos se entrega en los extras de la intención de su Actividad del lanzador.
Creo que esta respuesta de @ArthurThompson lo explica muy bien:
Cuando envía un mensaje de notificación con una carga de datos (notificación y datos) y la aplicación está en segundo plano, puede recuperar los datos de los extras de la intención que se inicia como resultado de que el usuario toque en la notificación.
De la muestra FCM que inicia la MainActivity cuando se realiza la notificación:
if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { String value = getIntent().getExtras().getString(key); Log.d(TAG, "Key: " + key + " Value: " + value); } }
Después de probar todas las respuestas y blogs surgió con la solución. Si alguien necesita por favor use este video como referencia
https://www.youtube.com/watch?v=hi8IPLNq59o
ADEMÁS del video para agregar intents do en MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { String user_id = "0"; String date = "0"; String hal_id = "0"; String M_view = "0"; if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); user_id = remoteMessage.getData().get("user_id"); date = remoteMessage.getData().get("date"); cal_id = remoteMessage.getData().get("hal_id"); M_view = remoteMessage.getData().get("M_view"); } String click_action = remoteMessage.getNotification().getClickAction(); //Calling method to generate notification sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action); } private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) { Intent intent = new Intent(click_action); intent.putExtra("user_id", user_id); intent.putExtra("date", date); intent.putExtra("hal_id", hal_id); intent.putExtra("M_view", M_view); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setSmallIcon(R.drawable.ic_launcher) .setContentTitle(messageTitle) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); }}
Y en la nueva actividad NotificationReceive en onCreate o onResume add this
notification_Y_N = (TextView) findViewById(R.id.notification_Y_N); user_id_text = (TextView) findViewById(R.id.user_id_text); Intent intent_o = getIntent(); String user_id = intent_o.getStringExtra("user_id"); String date = intent_o.getStringExtra("date"); String hal_id = intent_o.getStringExtra("hal_id"); String M_view = intent_o.getStringExtra("M_view"); notification_Y_N.setText(date); user_id_text.setText(hal_id);
- Apk instalado en el dispositivo pero no lo veo en las aplicaciones
- Desactivar grupo de menús de Android