Intégration des notifications push sur Android avec Parse et React Nat
17 min
notifications push pour react native sur android introduction ce guide vous apprendra à utiliser parse pour envoyer des notifications push à votre application react native sur android vous allez configurer firebase et configurer votre application back4app pour les envoyer via le tableau de bord et les fonctions cloud code à tout moment, vous pouvez accéder au projet android complet construit avec ce tutoriel sur nos dépôts github dépôt d'exemple javascript https //github com/templates back4app/react native js push notifications dépôt d'exemple typescript https //github com/templates back4app/react native ts push notifications prérequis pour compléter ce tutoriel, vous aurez besoin de une application react native créée et connectée à back4app https //www back4app com/docs/react native/parse sdk/react native sdk comprendre comment déployer une fonction cloud https //www back4app com/docs/get started/cloud functions sur back4app un compte actif chez google, afin que vous puissiez utiliser google firebase objectif envoyez des notifications push de parse à une application react native sur android, en utilisant le tableau de bord de back4app et les fonctions cloud code 1 configuration de firebase firebase est le fournisseur de services le plus utilisé pour envoyer et recevoir des notifications push sur android il est utilisé par un large éventail d'entreprises de nos jours, avec d'autres outils variés commençons par créer un projet firebase pour votre application en suivant les étapes 1 et 2 de cette documentation https //firebase google com/docs/android/setup#console après avoir créé votre application et avant de quitter la console de firebase, assurez vous de télécharger et de sauvegarder le fichier google services json et allez également dans les paramètres du projet, dans l'onglet “cloud messaging” et récupérez les clés suivantes clé du serveur; id de l'expéditeur 2 activation des notifications push sur back4app pour lier votre projet firebase avec back4app et activer l'envoi de notifications push via votre tableau de bord et cloud code, suivez ces étapes allez sur le site web de back4app https //www back4app com/ , connectez vous, trouvez votre application et cliquez sur \<font color="#2166ae">paramètres du serveur\</font> trouvez le bloc “notification push android” et cliquez sur \<font color="#2166ae">paramètres\</font> > \<font color="#2166ae">éditer\</font> le bloc “notification push android” ressemble à ceci 3\ ajoutez la \<font color="#2166ae">clé du serveur\</font> firebase au champ \<font color="#2166ae">clé api\</font> et l’ \<font color="#2166ae">id d'expéditeur\</font> au champ \<font color="#2166ae">id d'expéditeur gcm\</font> 4\ enregistrez le et vous avez terminé 3 installation et configuration des dépendances dans votre projet react native, installons la \<font color="#2166ae">react native push notification\</font> bibliothèque, qui intégrera l'application avec firebase et vous permettra de gérer toute notification reçue exécutez la commande suivante dans le répertoire racine de votre projet yarn add react native push notification après l'avoir installée, vous devez encore ajouter quelques configurations dans le \<font color="#2166ae">android/app/src/main/androidmanifest xml\</font> , \<font color="#2166ae">android/build gradle\</font> et \<font color="#2166ae">android/app/build gradle\</font> en suivant la documentation https //github com/zo0r/react native push notification assurez vous également d'ajouter dans le \<font color="#2166ae">androidmanifest xml\</font> un \<font color="#2166ae">meta data\</font> contenant l'identifiant de canal de notification par défaut pour votre application (utilisons \<font color="#2166ae">guidechannel\</font> comme exemple) vous pouvez ajouter le nom directement dans la directive ou l'inclure dans le \<font color="#2166ae">strings xml\</font> fichier de plus, placez le fichier \<font color="#2166ae">google services json\</font> de votre projet dans le répertoire \<font color="#2166ae">android/app\</font> 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" /> dans l'étape suivante, nous allons apprendre à utiliser cette bibliothèque et à la combiner avec parse 4 gestion des notifications push créons un fichier avec de nouvelles méthodes liées aux notifications push appelé \<font color="#2166ae">pushnotificationmethods js\</font> (ou \<font color="#2166ae">pushnotificationmethods tsx\</font> ) et ajoutons la fonction suivante, qui est responsable de l'initialisation de \<font color="#2166ae">react native push notification\</font> , de la création d'un canal de notification, et également de la configuration de parse pour reconnaître la configuration de push de notre appareil 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 } documentation open source plus d'informations sur le \<font color="#2166ae">parse installation\</font> classe peuvent être trouvées ici https //docs parseplatform org/js/guide/#push notifications notez que le gestionnaire d'événements \<font color="#2166ae">onnotification\</font> a un code qui déclenche une notification locale dans l'application après avoir reçu une notification distante parse exige ce code car firebase ne déclenche pas de notifications contextuelles avec des données par lui même plus d'informations à ce sujet et sur les types de notifications android peuvent être lues ici https //firebase google com/docs/cloud messaging/concept options#notifications and data messages appelez cette \<font color="#2166ae">configurepushnotifications\</font> méthode dans votre \<font color="#2166ae">app js\</font> (ou \<font color="#2166ae">app tsx\</font> ) fichier après avoir initialisé parse et avant de déclarer votre \<font color="#2166ae">app\</font> contenu 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(); construisez et exécutez l'application vous pouvez maintenant voir un \<font color="#2166ae">table d'installation\</font> dans le tableau de bord back4app de votre application avec une entrée correspondant à votre application 5 envoi de notifications push via le tableau de bord nous sommes maintenant prêts à envoyer la première notification push à notre application suivez les étapes ci dessous pour envoyer un message push via le tableau de bord de back4app allez sur le site web de back4app https //www back4app com/ , connectez vous, trouvez votre application et cliquez sur \<font color="#2166ae">tableau de bord\</font> cliquez sur \<font color="#2166ae">push\</font> > \<font color="#2166ae">envoyer une nouvelle notification push\</font> et créez un public pour votre notification push 3\ écrivez votre message et regardez l'aperçu en cliquant sur l'option \<font color="#2166ae">android\</font> 4\ si vous avez déjà examiné la notification push et que vous souhaitez l'envoyer, cliquez sur \<font color="#2166ae">envoyer push\</font> vous pouvez explorer les autres options pour la notification push à \<font color="#2166ae">parse dashboard\</font> là, il est également possible de consulter \<font color="#2166ae">les envois passés\</font> que vous avez envoyés et les \<font color="#2166ae">audiences\</font> que vous avez créées pour eux 6 envoi de notifications push via cloud code en utilisant le guide de démarrage des fonctions cloud https //www back4app com/docs/get started/cloud functions , vous pouvez détacher des méthodes réutilisables de votre front end et obtenir un contrôle complet de toutes vos ressources backend via la clé maître utilisons les fonctions de code cloud pour envoyer un message push tout d'abord, créez une fonction cloud appelée \<font color="#2166ae">sendpush\</font> qui appelle la méthode \<font color="#2166ae">parse push send\</font> il existe deux façons de sélectionner quels utilisateurs recevront la notification interroger la classe \<font color="#2166ae">parse installation\</font> ou via les noms de canaux de notification il est plus courant dans les applications android d'utiliser des canaux pour distinguer les utilisateurs, donc utilisons le assurez vous de déployer cette fonction sur back4app avant de continuer documentation open source veuillez consulter la documentation open source https //docs parseplatform org/js/guide/#sending options pour plus de détails sur la méthode \<font color="#2166ae">send\</font> 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 }); appelons maintenant la fonction depuis l'application react native ajoutez cette fonction au \<font color="#2166ae">pushnotificationmethods js\</font> (ou \<font color="#2166ae">pushnotificationmethods tsx\</font> ) fichier et appelez la dans un bouton à l'intérieur de l'écran principal de votre application 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 } notez que ce cas permettant à un utilisateur de déclencher une notification push par lui même n'est pas courant, nous l'avons utilisé ici juste pour montrer à quel point il est simple d'intégrer l'envoi de notifications push avec parse conclusion à la fin de ce guide, vous avez appris comment envoyer des notifications push en utilisant parse à votre application react native sur android dans le prochain guide, vous apprendrez comment les envoyer sur ios