LoginSignup
36
34

More than 5 years have passed since last update.

AndroidでReact Nativeを使ってPush通知を受け取る方法

Posted at

React Nativeの場合、iOSでPush通知する方法は表示で提供されていますが、
Androidの場合、自分で頑張るか外部のパッケージに頼ることになると思います。(04/2016現在)
ちょっと面倒がありそうな状況だから無難にGoogle Cloud Messagingをチョイスした方がいいよね、という判断で以下進めました。Parseもなくなるし。(Javaの時はParseしか使ったことなく、GCMも始めてなので回りくどいことしてたら教えてください)

Google APIsでプロジェクトを作る

「プロジェクトを作成」で今回用のプロジェクトを作ります。

GCMを許可してキーなどを得る

GCMのクイックスタートから
「プロジェクトでGCMで有効にすること」と、「キーの取得」が同時に出来るので上記URLから進めます。

「GET A CONFIGURATION FILE」をクリックして、
App nameに今回のプロジェクト名、package nameにAndroidのパッケージ名を入力してContinue...

Server API KeySender IDが得られます。

react-native-push-notificationを使う

自分はiOSでも標準のClassを使わずにこのライブラリを使ってます。

npm install react-native-push-notification

インストールした後、ReadMeにしたがって以下のファイルを編集します。

  • AndroidManifest.xml
  • android/settings.gradle
  • android/app/build.gradle

好きなとこでreact-native-push-notificationを呼ぶ

AndroidはiOSのようにpush通知許可のポップアップも出ないので、
App.js的な初めの方で呼ばれるComponentで好きに設定しましょう。

var PushNotification = require('react-native-push-notification');

PushNotification.configure({
  onRegister: function(token) {
    console.log( 'TOKEN:', token );
    // ここでサーバーにtokenを送るなりする。
    // token.tokenがstringのtokenのようです。    
  },

  onNotification: function(notification) {
    // 通知が届いたらにここにくる。
    // notification.foregroundがtrueならアプリを開いている時
    // notification.dataという感じで好きなデータをぶら下げて送って
    // ここで画面遷移したりなんやかんやする
    console.log( 'NOTIFICATION:', notification );
  },

  // 先ほど取得したsender IDを記述
  senderID: "YOUR GCM SENDER ID",
});

テスト送信する

よくcurlでテスト送信する方法が紹介されてます。
サーバーサイドがrailsの場合はgcmというgemがあったり色々あるので便利に使いましょう。
API KEYは以前の工程で取得したServer API Keyです。

%curl --header "Authorization: key=<API KEY>" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"<RegistrationID>\"],\"data\":{\"title\":\"Hello\",\"message\":\"Hello\"}}"

ここでミソとなるのはreact-native-push-notificationが以下の様なdataを想定していることです。

{
  title: "My Notification Title", // (optional)
  ticker: "My Notification Ticker", // (optional)
  largeIcon: "ic_launcher", // (optional)
  smallIcon: "ic_notification", // (optional)
  message: "My Notification Message" // (optional)
  data: {}
}

今触ってるverではsmallIconを空にしても表示されてしまうので、何かは絶対表示する仕様のようです。透明の画像とか用意したら騙せるかもしれません。どうしても嫌なら違うパッケージなり自前で頑張るということになりそうです。

そしてdataの更に下に自前のdataをぶら下げて、先ほどのonNotificationでなんやかんやするようにしています。

(メモ)通知アイコンの置き場所

最後にハマったとこメモですが、react-native-push-notificationはandroidネイティブのコードの方のdrawableではなくmipmapからしかic_notificationを探そうとしません。mipmapにイケてるアイコンを置きましょう。

以上、上手く送れたでしょうか?グッドラックです。

36
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
34