React Native
...
Push Notifications
Notificaciones Push en Android con Parse para React Native
17 min
notificaciones push para react native en android introducción esta guía te enseñará cómo usar parse para enviar notificaciones push a tu aplicación react native en android configurarás firebase y configurarás tu aplicación back4app para enviarlas a través del panel y funciones de cloud code en cualquier momento, puedes acceder al proyecto android completo construido con este tutorial en nuestros repositorios de github repositorio de ejemplo en javascript repositorio de ejemplo en typescript requisitos previos para completar este tutorial, necesitarás una aplicación react native creada y conectada a back4app entender cómo desplegar una función en la nube en back4app una cuenta activa en google, para que puedas usar google firebase objetivo envía notificaciones push desde parse a una aplicación de react native en android, utilizando el panel de control de back4app y las funciones de cloud code 1 configurando firebase firebase es el proveedor de servicios más utilizado para enviar y recibir notificaciones push en android es utilizado por una amplia gama de empresas en la actualidad, junto con otras diversas herramientas comencemos creando un proyecto de firebase para tu aplicación siguiendo los pasos 1 y 2 de esta documentación https //firebase google com/docs/android/setup#console después de crear tu aplicación y antes de salir de la consola de firebase, asegúrate de descargar y guardar el archivo google services json y también ve a la configuración del proyecto, en la pestaña “cloud messaging” y recupera las siguientes claves clave del servidor; id del remitente 2 habilitando notificaciones push en back4app para vincular tu proyecto de firebase con back4app y habilitar el envío de notificaciones push a través de tu panel de control y cloud code, sigue estos pasos ve a sitio web de back4app , inicia sesión, encuentra tu aplicación y haz clic en configuración del servidor configuración del servidor encuentra el bloque “notificación push de android” y haz clic en configuraciones configuraciones > editar editar el bloque “notificación push de android” se ve así 3\ agrega la clave del servidor clave del servidor de firebase al campo de clave api clave api y el id del remitente id del remitente al campo de id de gcm id de gcm 4\ guárdalo y habrás terminado 3 instalación y configuración de dependencias en tu proyecto de react native, instalemos la react native push notification react native push notification biblioteca, que integrará la aplicación con firebase y te permitirá manejar cualquier notificación recibida ejecuta el siguiente comando en el directorio raíz de tu proyecto después de instalarlo, aún necesitas agregar algunas configuraciones al android/app/src/main/androidmanifest xml android/app/src/main/androidmanifest xml , android/build gradle android/build gradle y android/app/build gradle android/app/build gradle siguiendo la documentación https //github com/zo0r/react native push notification asegúrate de agregar también en el androidmanifest xml androidmanifest xml un meta data meta data que contenga el id del canal de notificación predeterminado para tu aplicación (usaremos guidechannel guidechannel como nuestro ejemplo) puedes agregar el nombre directamente a la directiva o incluirlo en el strings xml strings xml archivo además, coloca el archivo google services json google services json de tu proyecto en el android/app android/app directorio 1 \<meta data 2 android\ name="com google firebase messaging default notification channel id" 3 android\ value="guidechannel" /> 4 \<! or > 5 \<meta data 6 android\ name="com google firebase messaging default notification channel id" 7 android\ value="@string/default notification channel id" /> en el siguiente paso, aprenderemos cómo usar esta biblioteca y combinarla con parse 4 manejo de notificaciones push vamos a crear un archivo con nuevos métodos relacionados con las notificaciones push llamado pushnotificationmethods js pushnotificationmethods js (o pushnotificationmethods tsx pushnotificationmethods tsx ) y agregar la siguiente función, que es responsable de inicializar el react native push notification react native push notification , crear un canal de notificación y también configurar parse para reconocer la configuración de push de nuestro dispositivo javascript 1 import pushnotification from 'react native push notification'; 2 import parse from 'parse/react native'; 3	 4 const channelid = 'guidechannel'; 5	 6 export async function configurepushnotifications() { 7 // initialize pushnotification 8 await pushnotification configure({ 9 // (required) called when a remote is received or opened, or local notification is opened 10 onnotification function (notification) { 11 // process the notification 12 console log('notification ', notification); 13 // if notification is remote and has data, trigger local notification to show popup 14 // this is needed for parse sent notifications because firebase doesn't trigger popup 15 // notifications with data by itself 16 if ( 17 notification data !== undefined && 18 notification data data !== undefined 19 ) { 20 try { 21 // notification data comes as a stringified json, so parsing is needed 22 const notificationdata = json parse(notification data data); 23 // json parse notifications from the dashboard and cloud code 24 // should contain the default `title` and `message` parameters 25 let title = 'notification title'; 26 if (notificationdata title !== undefined) { 27 title = notificationdata title; 28 } 29 let message = 'noticiation message'; 30 if (notificationdata message !== undefined) { 31 message = notificationdata message; 32 } 33 // text parse notifications from the dashboard only have an `alert` parameter 34 if (notificationdata alert !== undefined) { 35 message = notificationdata alert; 36 } 37 pushnotification localnotification({ 38 channelid channelid, 39 title title, 40 message message, 41 }); 42 } catch (error) { 43 console log(`error triggering local notification ${error}`); 44 } 45 } 46 }, 47	 48 onregister async function (token) { 49 console log(`registered with device token ${token token}`); 50 let devicetoken = token token; 51	 52 // create the notification channel, required for android notifications 53 await pushnotification createchannel({ 54 channelid channelid, 55 channelname 'guide channel', 56 }); 57 console log('notification channel created!'); 58	 59 // create a parse installation, that will link our application's push notification 60 // to the parse server 61 try { 62 const installationid = await parse getinstallationid(); 63 const installation = new parse installation(); 64 // make sure to change any needed value from the following 65 installation set('devicetype', 'android'); 66 installation set('gcmsenderid', 'your gcm sender id'); 67 installation set('pushtype', 'gcm'); 68 installation set('appidentifier', 'your app identifier(package name)'); 69 installation set('parseversion', '3 2 0'); 70 installation set('appname', 'back4appguidepushnotifications'); 71 installation set('appversion', '1 0'); 72 installation set('localeidentifier', 'pt br'); 73 installation set('badge', 0); // set initial notification badge number 74 installation set('timezone', 'america/sao paulo'); 75 installation set('installationid', installationid); 76 installation set('channels', \[channelid]); 77 installation set('devicetoken', devicetoken); 78 await installation save(); 79 console log(`created new parse installation ${installation}`); 80 } catch (error) { 81 console log(error message); 82 } 83 }, 84 popinitialnotification true, 85 requestpermissions true, 86 }); 87 }1 import pushnotification from 'react native push notification'; 2 import parse from 'parse/react native'; 3	 4 const channelid string = 'guidechannel'; 5	 6 export async function configurepushnotifications() { 7 // initialize pushnotification 8 await pushnotification configure({ 9 // (required) called when a remote is received or opened, or local notification is opened 10 onnotification function (notification object) { 11 // process the notification 12 console log('notification ', notification); 13 // if notification is remote and has data, trigger local notification to show popup 14 // this is needed for parse sent notifications because firebase doesn't trigger popup 15 // notifications with data by itself 16 if ( 17 notification data !== undefined && 18 notification data data !== undefined 19 ) { 20 try { 21 // notification data comes as a stringified json, so parsing is needed 22 const notificationdata = json parse(notification data data); 23 // json parse notifications from the dashboard and cloud code 24 // should contain the default `title` and `message` parameters 25 let title string = 'notification title'; 26 if (notificationdata title !== undefined) { 27 title = notificationdata title; 28 } 29 let message string = 'noticiation message'; 30 if (notificationdata message !== undefined) { 31 message = notificationdata message; 32 } 33 // text parse notifications from the dashboard only have an `alert` parameter 34 if (notificationdata alert !== undefined) { 35 message = notificationdata alert; 36 } 37 pushnotification localnotification({ 38 channelid channelid, 39 title title, 40 message message, 41 }); 42 } catch (error any) { 43 console log(`error triggering local notification ${error}`); 44 } 45 } 46 }, 47	 48 onregister async function (token {os string; token string}) { 49 console log(`registered with device token ${token token}`); 50 let devicetoken string = token token; 51	 52 // create the notification channel, required for android notifications 53 await pushnotification createchannel({ 54 channelid channelid, 55 channelname 'guide channel', 56 }); 57 console log('notification channel created!'); 58	 59 // create a parse installation, that will link our application's push notification 60 // to the parse server 61 try { 62 const installationid = await parse getinstallationid(); 63 const installation = new parse installation(); 64 // make sure to change any needed value from the following 65 installation set('devicetype', 'android'); 66 installation set('gcmsenderid', 'your gcm sender id'); 67 installation set('pushtype', 'gcm'); 68 installation set('appidentifier', 'your app identifier(package name)'); 69 installation set('parseversion', '3 2 0'); 70 installation set('appname', 'back4appguidepushnotifications'); 71 installation set('appversion', '1 0'); 72 installation set('localeidentifier', 'pt br'); 73 installation set('badge', 0); // set initial notification badge number 74 installation set('timezone', 'america/sao paulo'); 75 installation set('installationid', installationid); 76 installation set('channels', \[channelid]); 77 installation set('devicetoken', devicetoken); 78 await installation save(); 79 console log(`created new parse installation ${installation}`); 80 } catch (error) { 81 console log(error message); 82 } 83 }, 84 popinitialnotification true, 85 requestpermissions true, 86 }); 87 } documentación de código abierto más información sobre la parse installation parse installation clase se puede encontrar aquí https //docs parseplatform org/js/guide/#push notifications tenga en cuenta que el controlador de eventos onnotification onnotification tiene un código que activa una notificación local en la aplicación después de recibir una remota parse requiere este código porque firebase no activa notificaciones emergentes con datos por sí mismo más sobre eso y los tipos de notificaciones de android se pueden leer aquí llama a este configurepushnotifications configurepushnotifications método en tu app js app js (o app tsx app tsx ) archivo después de inicializar parse y antes de declarar tu app app contenido app js 1 // other imports 2 // 3 import {configurepushnotifications} from ' /src/pushnotificationmethods'; 4	 5 // your parse initialization configuration goes here 6 // 7	 8 // initialize pushnotifications 9 configurepushnotifications(); construye y ejecuta la aplicación ahora puedes ver una instalación instalación tabla en el panel de control de back4app de tu aplicación con una entrada correspondiente a tu aplicación 5 enviando notificaciones push a través del panel de control ahora estamos listos para enviar la primera notificación push a nuestra aplicación sigue los pasos a continuación para enviar un mensaje push a través del panel de control de back4app ve a sitio web de back4app , inicia sesión, encuentra tu aplicación y haz clic en panel de control panel de control haz clic en push push > enviar nueva notificación push enviar nueva notificación push y crea una audiencia para tu notificación push 3\ escribe tu mensaje y mira la vista previa haciendo clic en la opción android android 4\ si ya has revisado la notificación push y deseas enviarla, haz clic en enviar push enviar push puedes explorar las otras opciones para notificaciones push en parse dashboard parse dashboard allí, también es posible ver notificaciones pasadas notificaciones pasadas que enviaste y las audiencias audiencias que creaste para ellas 6 enviando notificaciones push a través de cloud code usando guía de inicio de funciones en la nube https //www back4app com/docs/get started/cloud functions , puedes desacoplar métodos reutilizables de tu front end y obtener control total de todos tus recursos de backend a través de la clave maestra utilicemos funciones de código en la nube para enviar un mensaje push primero, crea una función en la nube llamada sendpush sendpush que llame al método parse push send parse push send hay dos formas de seleccionar qué usuarios recibirán la notificación consultando la clase parse installation parse installation o a través de nombres de canales de notificación es más común en aplicaciones de android usar canales para distinguir entre los usuarios, así que usémoslo asegúrate de implementar esta función en back4app antes de continuar documentación de código abierto por favor, consulta la documentación de código abierto https //docs parseplatform org/js/guide/#sending options para más detalles sobre el método send send 1 parse cloud define('sendpush', async (request) => { 2 try { 3 await parse push send({ 4 channels \[ 'guidechannel' ], 5 data { 6 message 'test message', 7 title 'back4app guide notification' 8 } 9 }, { usemasterkey true }); 10 return true; 11 } catch (error) { 12 return `error ${error}` 13 } 14 }); ahora llamemos a la función desde la aplicación de react native agrega esta función al pushnotificationmethods js pushnotificationmethods js (o pushnotificationmethods tsx pushnotificationmethods tsx ) archivo y llámala en un botón dentro de la pantalla principal de tu aplicación 1 export async function sendnotification() { 2 try { 3 await parse cloud run('sendpush'); 4 console log('success!'); 5 } catch (error any) { 6 console log(`error ${error}`); 7 } 8 } ten en cuenta que este caso de permitir que un usuario active una notificación push por sí mismo no es común, lo usamos aquí solo para mostrar lo simple que es integrar el envío de notificaciones push con parse conclusión al final de esta guía, aprendiste cómo enviar notificaciones push usando parse a tu aplicación de react native en android en la próxima guía, aprenderás cómo enviarlas en ios