2015年4月8日 星期三

Codova推播訊息教學

 目前Google Cloud Message(GCM)是推播訊息的主流技術,當然要來學習如何用Codova相關技術來完成推播的功能,如果本人的訊息有誤,也請高人多多指教,希望這篇文章對於對推播有困擾的朋友有些幫助。

步驟1: 先到Google console API, 開啟google Cloud Messaging For Android

登入Google Console API 取得Project ID




點選左方API Project的選單àServicesà 開啟Google Cloud Messaging for Android



步驟2: 申請Service key



 如果有限定IP才允許使用推播功能,請輸入IP 位址,否則空白即可


步驟3:佈署到客戶端的APP程式

本範例是使用第三方元件PubNub示範推播功能,以下是參考的必要元件
<script type="text/javascript" src="js/PushNotification.js"></script>
<script type="text/javascript" src="//cdn.pubnub.com/pubnub-3.7.4.min.js"></script>
<script src="cordova.js"></script>
<script src="scripts/angular.min.js"></script>

以下範例是使用angular接收來自push Notification的語法
     var app = angular.module("touchModle", []);
        app.factory('PushService', function () {
            function onDeviceReady() {
                try {
                    pushNotification = window.plugins.pushNotification;
                    if (device.platform == 'android' || device.platform == 'Android') {
                        //android :註冊IDecb參數是推播時執行的函數
                        pushNotification.register(successHandler, errorHandler, { "senderID": "專案ID", "ecb": "onNotificationGCM" });                        
} else {
//其他裝置 :註冊ID
                        pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" });
                    }
                }
                catch (err) {
                    txt = "There was an error on this page.\n\n";
                    txt += "Error description: " + err.message + "\n\n";
                    alert(txt);
                }
            }
            function successHandler(result) {
                alert("success OK");
            }
            function errorHandler(error) {
                alert('失敗');
            }          
            return {
                init: function () {
                    document.addEventListener('deviceready', onDeviceReady, false);
                }
            }
        })
// 宣告在javascript, pushNotification ecb 才能執行到此函數
        function onNotificationGCM(e) {
            var xmlhttp = new XMLHttpRequest();
            switch (e.event) {
                case 'registered':
                    if (e.regid.length > 0) {
                        xmlhttp.open("GET", "http://192.168.1.63/codovaWebAPI/api/apiPatient?registID=" + e.regid, true); // 儲存手機的註冊ID
                        xmlhttp.send();
                    }
                    break;
                case 'message':
                    if (e.foreground) {
                        // When the app is running foreground.
                        alert(e.message)
                    }
                    break;
                case 'error':
                    alert("error" + e.msg);
                    break;
                default: alert('An unknown event was received');
                    break;
            }
        }
        app.controller("touchController", function ($http, $scope, PushService) {
            PushService.init();
        });

步驟4:佈署Server

先宣告推播物件,首先把之前申請Service key 填寫在GoogleAppID,再把Google專案的ID填寫在SENDER_ID


public string SendNotification(string deviceId, string message)
        {
            string GoogleAppID = "xxxxxxc"; //Google service ikey
            var SENDER_ID = "xxxxxxx"; //Google project  ID
            var value = System.Web.HttpUtility.UrlEncode(message); //如果有傳遞中文,需要編碼           
            tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));           
            string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
       
            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            tRequest.ContentLength = byteArray.Length;
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
            return sResponseFromServer;
        }

呼叫推播的物件(MVC架構的controller)
       [HttpPost]
        public ActionResult Index(string device, string message)
        {
             pushMessage pushMessageObj = new pushMessage();
             pushMessageObj.SendNotification(device, message);
             return View();
        }

(MVC架構的View)
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <input type="text" id="device" name="device" />
    <input type="text" id="message" name="message"  />
    <input type="submit" value="推播" />
}

    以上是作者的經驗,如果有更好的其他推播方式,也歡迎各位高手留言,目前只有針對Android 的推播方式…  後續有機會再研究IOS的推播方式,感謝各位如此有耐心看完這篇文章。





1 則留言: