React Native
...
Push Notifications
Android向けReact NativeのParseプッシュ通知の実装
15 分
android向けreact nativeのプッシュ通知 はじめに このガイドでは、parseを使用してandroidのreact nativeアプリケーションにプッシュ通知を送信する方法を学びます。firebaseを設定し、ダッシュボードとcloud code関数を介して通知を送信するためにback4appアプリを構成します。 いつでも、このチュートリアルで構築された完全なandroidプロジェクトに私たちのgithubリポジトリでアクセスできます javascriptのサンプルリポジトリ typescriptのサンプルリポジトリ 前提条件 このチュートリアルを完了するには、次のものが必要です: 作成されたreact nativeアプリと back4appに接続された どのように クラウド関数をデプロイするか を理解すること。 google firebaseを使用するためのgoogleのアクティブアカウント。 目標 parseからreact nativeアプリケーションへのプッシュ通知を、back4appのダッシュボードとcloud code機能を使用してandroidで送信します。 1 firebaseの設定 firebaseは、androidでプッシュ通知を送受信するために最も使用されているサービスプロバイダーです。現在、さまざまな企業によって使用されており、他のさまざまなツールとともに利用されています。まず、次の手順1と2に従って、アプリ用のfirebaseプロジェクトを作成しましょう。 このドキュメント https //firebase google com/docs/android/setup#console から。 アプリを作成した後、firebaseのコンソールを終了する前に、google services jsonファイルをダウンロードして保存し、「cloud messaging」タブのプロジェクト設定に移動して、次のキーを取得してください サーバーキー; 送信者id。 2 back4appでのプッシュ通知の有効化 firebaseプロジェクトをback4appにリンクし、ダッシュボードとクラウドコードを通じてプッシュ通知を送信できるようにするには、以下の手順に従ってください 「 back4appウェブサイト 」にアクセスし、ログインしてアプリを見つけ、「 サーバー設定 サーバー設定 」をクリックします。 「androidプッシュ通知」ブロックを見つけ、「 設定 設定 」をクリックし、「 編集 編集 」をクリックします。「androidプッシュ通知」ブロックはこのようになります 3\ firebaseの サーバーキー サーバーキー を apiキー apiキー フィールドに追加し、 送信者id 送信者id を gcm送信者id gcm送信者id フィールドに追加します。 4\ 保存して完了です。 3 依存関係のインストールと設定 あなたのreact nativeプロジェクトに、 react native push notification react native push notification ライブラリをインストールしましょう。このライブラリはアプリケーションをfirebaseと統合し、受信した通知を処理できるようにします。プロジェクトのルートディレクトリで次のコマンドを実行してください インストール後、次のファイルにいくつかの設定を追加する必要があります。 android/app/src/main/androidmanifest xml android/app/src/main/androidmanifest xml , android/build gradle android/build gradle および android/app/build gradle android/app/build gradle 、ライブラリの ドキュメント https //github com/zo0r/react native push notification を参照してください。 また、 androidmanifest xml androidmanifest xml ファイルに、アプリケーションのデフォルト通知チャネルidを含む meta data meta data を追加することを忘れないでください(例として guidechannel guidechannel を使用します)。名前をディレクティブに直接追加するか、 strings xml strings xml ファイルに含めることができます。また、プロジェクトの google services json google services json ファイルを android/app android/app ディレクトリに配置してください。 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" /> 次のステップでは、このライブラリの使い方を学び、parseと組み合わせる方法を学びます。 4 プッシュ通知の処理 プッシュ通知に関連する新しいメソッドを持つファイルを作成しましょう。ファイル名は pushnotificationmethods js pushnotificationmethods js (または pushnotificationmethods tsx pushnotificationmethods tsx )で、次の関数を追加します。この関数は、 react native push notification react native push notification を初期化し、通知チャネルを作成し、私たちのデバイスのプッシュ設定を認識するためにparseを設定します 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 } オープンソースドキュメント 次の情報は parse installation parse installation クラスについて見つけることができます こちら https //docs parseplatform org/js/guide/#push notifications イベントハンドラー onnotification onnotification メソッドには、リモート通知を受信した後にアプリ内でローカル通知をトリガーするコードがあります。parseはこのコードを必要とします。なぜなら、firebaseはデータを持つポップアップ通知を自動的にトリガーしないからです。これに関する詳細やandroid通知の種類については こちら をお読みください。 この configurepushnotifications configurepushnotifications メソッドを app js app js (または app tsx app tsx ) ファイルで、parseを初期化した後、あなたの app app コンテンツを宣言する前に呼び出してください。 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(); アプリケーションをビルドして実行します。これで、アプリのback4appダッシュボードに、アプリに対応するエントリを持つ インストール インストール テーブルが表示されます。 5 ダッシュボードを介してプッシュ通知を送信する アプリに最初のプッシュ通知を送信する準備が整いました。以下の手順に従って、back4appのダッシュボードを介してプッシュメッセージを送信してください 次に進みます back4appのウェブサイト , ログインし、アプリを見つけて ダッシュボード ダッシュボード をクリックします。 次に プッシュ プッシュ > 新しいプッシュを送信 新しいプッシュを送信 をクリックし、プッシュ通知のオーディエンスを作成します。 3\ メッセージを書き、 android android オプションをクリックしてプレビューを確認します。 4\ もしプッシュ通知をすでに確認していて、送信したい場合は、 プッシュを送信 プッシュを送信 をクリックしてください。 プッシュ通知の他のオプションを探すには、 parseダッシュボード parseダッシュボード を訪れてください。 そこでは、あなたが送信した 過去のプッシュ 過去のプッシュ や、あなたが作成した オーディエンス オーディエンス を確認することもできます。 6 クラウドコードを使用したプッシュ通知の送信 「 クラウド関数のスターターガイド https //www back4app com/docs/get started/cloud functions 」を使用すると、フロントエンドから再利用可能なメソッドを切り離し、マスターキーを介してすべてのバックエンドリソースを完全に制御できます。 プッシュメッセージを送信するためにクラウドコード関数を使用しましょう。まず、「 sendpush sendpush 」という名前のクラウド関数を作成し、 parse push send parse push send メソッドを呼び出します。通知を受け取るユーザーを選択する方法は2つあります: parse installation parse installation クラスをクエリするか、通知チャネル名を使用することです。androidアプリでは、ユーザーを区別するためにチャネルを使用することが一般的なので、これを使用しましょう。この関数をback4appにデプロイすることを忘れないでください。 オープンソースドキュメント 「 オープンソースドキュメント https //docs parseplatform org/js/guide/#sending options 」を確認して、 送信 送信 メソッドの詳細を確認してください。 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 }); react native アプリから関数を呼び出しましょう。この関数を pushnotificationmethods js pushnotificationmethods js (または pushnotificationmethods tsx pushnotificationmethods tsx ) ファイルに追加し、アプリケーションのメイン画面内のボタンで呼び出します 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 } ユーザーが自分でプッシュ通知をトリガーできるこのケースは一般的ではないことに注意してください。ここでは、parseとのプッシュ通知送信の統合がどれほど簡単であるかを示すために使用しました。 結論 このガイドの最後に、android の react native アプリケーションに parse を使用してプッシュ通知を送信する方法を学びました。次のガイドでは、ios でそれらを送信する方法を学びます。