cordovaでpush通知サンプルその1
Push通知
なんか勝手にアプリにデータを送信するちょっと便利かつ、迷惑な機能
参考にしたもの(といいますか基本パクっています。メモ代わりって感じ)
Cordova GCMから送信したAndoroidのプッシュ通知を受け取るアプリケーションの作成 - Symfoware
cordovaで作成
cd cordova cordova create test01 app.example.test01 Test01 cd test01/ cordova platforms add android cordova plugin add org.apache.cordova.device cordova plugin add org.apache.cordova.console cordova plugin add https://github.com/phonegap-build/PushPlugin.git
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="msapplication-tap-highlight" content="no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; connect-src *; img-src *; frame-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval' 'unsafe-inline' *;"> <title>Push!</title> </head> <body> <h1>Pushテスト</h1> <ul id="app-status-ul"></ul> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script> <script type="text/javascript"> $(function() { var pushNotification; document.addEventListener("deviceready", function(){ pushNotification = window.plugins.pushNotification; // Android 通知の登録が成功した場合 var successHandler = function successHandler(result) { $("#app-status-ul").append('<li>result = ' + result + '</li>'); }; // iOS 通知の登録が成功した場合 function tokenHandler (result) { alert('device token = ' + result); } // 通知の登録が失敗した場合 var errorHandler = function(error) { $("#app-status-ul").append('<li>error = ' + error + '</li>'); }; $("#app-status-ul").append('<li>registering ' + device.platform + '</li>'); if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){ pushNotification.register( successHandler, errorHandler, { // ここをSender ID(プロジェクト番号)に変更 "senderID":"1234567890123", "ecb":"onNotification" }); } else { pushNotification.register( tokenHandler, errorHandler, { "badge":"true", "sound":"true", "alert":"true", "ecb":"onNotificationAPN" // iOSは試せないので一旦保留 }); } }); }); // androidの通知 function onNotification(e) { $("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>'); switch( e.event ) { case 'registered': if ( e.regid.length > 0 ) { $("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>"); // Your GCM push server needs to know the regID before it can push to this device // here is where you might want to send it the regID for later use. console.log("regID = " + e.regid); } break; case 'message': // if this flag is set, this notification happened while we were in the foreground. // you might want to play a sound to get the user's attention, throw up a dialog, etc. if ( e.foreground ) { $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>'); // on Android soundname is outside the payload. // On Amazon FireOS all custom attributes are contained within payload var soundfile = e.soundname || e.payload.sound; // if the notification contains a soundname, play it. var my_media = new Media("/android_asset/www/"+ soundfile); my_media.play(); } else { // otherwise we were launched because the user touched a notification in the notification tray. if ( e.coldstart ) { $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>'); } else { $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>'); } } $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>'); //Only works for GCM $("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>'); //Only works on Amazon Fire OS $status.append('<li>MESSAGE -> TIME: ' + e.payload.timeStamp + '</li>'); break; case 'error': $("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>'); break; default: $("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>'); break; } } // iOSの通知 function onNotificationAPN (event) { if ( event.alert ) { navigator.notification.alert(event.alert); } if ( event.sound ) { var snd = new Media(event.sound); snd.play(); } if ( event.badge ) { pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge); } } </script> </body> </html>
phpによるサーバからの送信プログラム
<?php $googleApiUrl = "https://android.googleapis.com/gcm/send"; $registrationIds = [ 「console.log("regID = " + e.regid);」で取得したID ]; $apiKey = "APIKEYを設定する"; // sendデータ $send_data = array( "the_message" => 'You have x new friends', "param2" => 'value2' ); //ヘッダーの文字列作成 $header_string = "Content-Type:application/json"."\r\n" . "Authorization:key=". $apiKey . "\r\n" ; $content_array = array( 'data' => $send_data , 'registration_ids' => $registrationIds , 'collapse_key' => 'google_cloud_messaging_test' ); // JSON形式に変換 $content_json = json_encode($content_array); $options_array = array(); //送信メソッド $options_array["http"]["method"] = "POST"; //ヘッダー $options_array["http"]["header"] = $header_string; //コンテント $options_array["http"]["content"] = $content_json; //コンテキストインスタンスを作成 $context = stream_context_create(); //コンテキストにオプション情報(ヘッダー情報、コンテントの内容、送信メソッドなど)をセット stream_context_set_option( $context, $options_array ); //APIへのクエリ送信、戻ってきたデータの受取 $return_data = file_get_contents( $googleApiUrl, //接続先のURL false, //パス検索 $context //送信する内容(リソースコンテクスト) );
結果
右の方にあるスマホにpushした場合にメッセージがなんか追加されるようになりました。
所感
ダイアログがでるかはともかく、なんかの通知を行う場合には役に立つと思われる。
アプリを動かしていない場合に通知メッセージがでるようにする修正も入れてみる。
cordovaの場合は大半をプラグインの方で対応しているので結構便利なかんじ