m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

cordovaでpush通知サンプルその2

Push通知

なんか勝手にアプリにデータを送信するちょっと便利かつ、迷惑な機能

参考にしたもの(といいますか基本パクっています。メモ代わりって感じ)

Cordova GCMからのプッシュ内容を通知領域に表示する - Symfoware

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":"1006098093208",
                            "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 ( e.foreground ) {
                    $("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
                    console.log("=== message.foreground ===");
                } else {
                    // 通知領域からの新規起動
                    if ( e.coldstart ) {
                        console.log("=== message.background.coldstart ===");

                    // 通知領域からバッググラウンドにいたアプリを呼び出し
                    } else {
                        console.log("=== message.background.non coldstart ===");
                    }
                }
                $("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.info + '</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(
        "title" => "プッシュテスト",
        "message" => 'プッシュ通知テスト',
        "info" => 'プッシュ通知テストの詳細です。'
    );

    //ヘッダーの文字列作成
    $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                //送信する内容(リソースコンテクスト)
    );

※送信するデータは

    // sendデータ
    $send_data = array(
        "title" => "プッシュテスト",
        "message" => 'プッシュ通知テスト',
        "info" => 'プッシュ通知テストの詳細です。'
    );

のような形で送信する。
title:通知バーに表示されるタイトル
message:通知バーの表示される内容
info:通知処理で画面がアクティブになった際に取得される値

結果

起動時は画面に反映、未起動時は起動して設定する

所感

お知らせなどを表示するには便利な機能のようです。うまく動かし方はまあおいといてw