React Native
...
Push Notifications
Push-Benachrichtigungen in React Native mit Parse und Firebase
17 min
push benachrichtigungen für react native auf android einführung dieser leitfaden zeigt ihnen, wie sie parse verwenden, um push benachrichtigungen an ihre react native anwendung auf android zu senden sie werden firebase einrichten und ihre back4app app konfigurieren, um sie über das dashboard und cloud code funktionen zu senden jederzeit können sie das vollständige android projekt, das mit diesem tutorial erstellt wurde, in unseren github repositories einsehen javascript beispiel repository typescript beispiel repository voraussetzungen um dieses tutorial abzuschließen, benötigen sie eine react native app, die erstellt und mit back4app verbunden ist verstehen, wie man eine cloud funktion bereitstellt auf back4app ein aktives konto bei google, damit sie google firebase verwenden können ziel senden sie push benachrichtigungen von parse an eine react native anwendung auf android, indem sie das dashboard von back4app und cloud code funktionen verwenden 1 firebase einrichten firebase ist der am häufigsten verwendete dienstanbieter zum senden und empfangen von push benachrichtigungen auf android es wird heutzutage von einer vielzahl von unternehmen zusammen mit anderen verschiedenen tools verwendet lassen sie uns damit beginnen, ein firebase projekt für ihre app zu erstellen, indem wir die schritte 1 und 2 aus dieser dokumentation https //firebase google com/docs/android/setup#console nachdem sie ihre app erstellt haben und bevor sie die firebase konsole verlassen, stellen sie sicher, dass sie die datei google services json herunterladen und speichern und auch zu den projekteinstellungen gehen, über den tab „cloud messaging“ und die folgenden schlüssel abrufen server schlüssel; sender id 2 push benachrichtigungen auf back4app aktivieren um ihr firebase projekt mit back4app zu verknüpfen und das senden von push benachrichtigungen über ihr dashboard und cloud code zu aktivieren, befolgen sie diese schritte gehen sie zu back4app website , melden sie sich an, suchen sie ihre app und klicken sie auf servereinstellungen servereinstellungen suchen sie den block „android push benachrichtigung“ und klicken sie auf einstellungen einstellungen > bearbeiten bearbeiten der block „android push benachrichtigung“ sieht so aus 3\ fügen sie den firebase server schlüssel server schlüssel in das api schlüssel api schlüssel feld und die sender id sender id in das gcm sender id gcm sender id feld ein 4\ speichern sie es und sie sind fertig 3 abhängigkeiten installieren und einrichten in deinem react native projekt lass uns die react native push notification react native push notification bibliothek installieren, die die anwendung mit firebase integriert und es dir ermöglicht, empfangene benachrichtigungen zu verarbeiten führe den folgenden befehl im stammverzeichnis deines projekts aus nach der installation musst du noch einige konfigurationen in die android/app/src/main/androidmanifest xml android/app/src/main/androidmanifest xml , android/build gradle android/build gradle und android/app/build gradle android/app/build gradle gemäß der dokumentation https //github com/zo0r/react native push notification stelle sicher, dass du auch in die androidmanifest xml androidmanifest xml datei ein meta data meta data einfügst, die die standardbenachrichtigungskanal id für deine anwendung enthält (lass uns guidechannel guidechannel als unser beispiel verwenden) du kannst den namen direkt in die direktive einfügen oder ihn in die strings xml strings xml datei einfügen platziere auch die google services json google services json datei deines projekts im android/app android/app verzeichnis 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" /> im nächsten schritt werden wir lernen, wie man diese bibliothek verwendet und sie mit parse kombiniert 4 umgang mit push benachrichtigungen lass uns eine datei mit neuen methoden für push benachrichtigungen erstellen, die pushnotificationmethods js pushnotificationmethods js heißt (oder pushnotificationmethods tsx pushnotificationmethods tsx ) und die folgende funktion hinzufügen, die dafür verantwortlich ist, die react native push notification react native push notification , einen benachrichtigungskanal zu erstellen und auch parse einzurichten, um die push konfiguration unseres geräts zu erkennen 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 } open source dokumentation weitere informationen zur parse installation parse installation klasse finden sie hier https //docs parseplatform org/js/guide/#push notifications bitte beachten sie, dass der ereignis handler onnotification onnotification methode einen code enthält, der eine lokale benachrichtigung in der app auslöst, nachdem eine entfernte empfangen wurde parse benötigt diesen code, da firebase keine popup benachrichtigungen mit daten von sich aus auslöst mehr dazu und zu den android benachrichtigungstypen kann hier gelesen werden rufen sie diese configurepushnotifications configurepushnotifications methode in ihrer app js app js (oder app tsx app tsx ) datei auf, nachdem sie parse initialisiert haben und bevor sie ihren app app inhalt deklarieren 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(); bauen und führen sie die anwendung aus sie können jetzt eine installation installation tabelle im back4app dashboard ihrer app sehen, mit einem eintrag, der ihrer app entspricht 5 push benachrichtigungen über das dashboard senden wir sind jetzt bereit, die erste push benachrichtigung an unsere app zu senden befolgen sie die folgenden schritte, um eine push nachricht über das dashboard von back4app zu senden gehen sie zu back4app website , melden sie sich an, finden sie ihre app und klicken sie auf dashboard dashboard klicken sie auf push push > neue push senden neue push senden und erstellen sie ein publikum für ihre push benachrichtigung 3\ schreiben sie ihre nachricht und sehen sie sich die vorschau an, indem sie auf die android android option klicken 4\ wenn sie die push benachrichtigung bereits überprüft haben und sie senden möchten, klicken sie auf push senden push senden sie können die anderen optionen für push benachrichtigungen unter parse dashboard parse dashboard dort ist es auch möglich, die vergangenen pushs vergangenen pushs zu sehen, die sie gesendet haben, und die zielgruppen zielgruppen die sie für sie erstellt haben 6 senden von push benachrichtigungen über cloud code mit cloud funktionen starterleitfaden https //www back4app com/docs/get started/cloud functions , können sie wiederverwendbare methoden von ihrem frontend trennen und die vollständige kontrolle über alle ihre backend ressourcen über den master schlüssel erhalten lassen sie uns cloud code funktionen verwenden, um eine push nachricht zu senden zuerst erstellen sie eine cloud funktion namens sendpush sendpush die die parse push send parse push send methode aufruft es gibt zwei möglichkeiten, auszuwählen, welche benutzer die benachrichtigung erhalten abfragen der parse installation parse installation klasse oder über benachrichtigungskanalnamen es ist üblicher in android apps, kanäle zu verwenden, um zwischen den benutzern zu unterscheiden, also lassen sie uns das verwenden stellen sie sicher, dass sie diese funktion auf back4app bereitstellen, bevor sie fortfahren open source dokumentation bitte überprüfen sie die open source dokumentation https //docs parseplatform org/js/guide/#sending options für weitere details zur send send methode 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 }); lass uns jetzt die funktion aus der react native app aufrufen füge diese funktion zu der pushnotificationmethods js pushnotificationmethods js (oder pushnotificationmethods tsx pushnotificationmethods tsx ) datei hinzu und rufe sie in einem button innerhalb des hauptbildschirms deiner anwendung auf 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 } beachte, dass dieser fall, in dem ein benutzer selbst eine push benachrichtigung auslösen kann, nicht üblich ist wir haben ihn hier verwendet, um zu zeigen, wie einfach es ist, das senden von push benachrichtigungen mit parse zu integrieren fazit am ende dieses leitfadens hast du gelernt, wie man push benachrichtigungen mit parse an deine react native anwendung auf android sendet im nächsten leitfaden wirst du lernen, wie man sie auf ios sendet