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