用nodejs部署phonegap push message for android环境的步骤

参考 http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
1 安装jdk/jre
配置环境变量JAVA_HOME,添加到PATH

2 安装ant
npm install -g ant
新增环境变量ANT_HOME,变量值为C:\apache-ant-1.9.4。添加到PATH

3 安装git
新增环境变量GIT_HOME 变量值为实际路径,如C:\Program Files (x86)\Git
要将GIT_HOME/bin添加到path环境变量。


5 安装android sdk(19以上版本)
将sdk放在某个目录下,然后在环境变量中新增ANDROID_HOME 设置值为android sdk的地址。如E:\android\sdk

6 设置PATH变量。将以上新增的变量都添加到PATH中。如下:
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Dell\Dell Data Protection\Access\Advanced\Wave\Gemalto\Access Client\v5\;C:\Program Files (x86)\Security Innovation\SI TSS\bin\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\nodejs\;C:\Program Files\TortoiseGit\bin;%ANT_HOME%\bin;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools;%GIT_HOME%\bin

7 创建项目
phonegap create PushNotificationSample --id "com.pushapp" --name "PushNotificationApp"

8 安装push plugin了。
执行 
phonegap local plugin add https://github.com/phonegap-build/PushPlugin
安装plugin时会提示没有C:\Users\davidhuang\AppData\Local\Temp\plugman下的某个目录。为了能安装plugin还要要手动添加以下目录(非常恶心)
C:\Users\davidhuang\AppData\Local\Temp\plugman
安装成功后,在plugins目录下多了com.phonegap.plugins.PushPlugin

9 安装android平台
执行phonegap local build android
注意,这里会提示没有avd模拟器。要手动打开avd,开启一个android模拟器。
安装成功后在platforms下就多了个android目录

10 添加<script type="text/javascript" src="js/PushNotification.js"></script>

11 在config.xml添加<gap:plugin name="com.adobe.plugins.pushplugin" />

12 修改index.js 实现注册ID和接收消息的功能

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
		var pushNotification = window.plugins.pushNotification;
		pushNotification.register(app.successHandler, app.errorHandler, 
			{"senderID":"621074495309","ecb":"app.onNotificationGCM"});

        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
	// result contains any message sent from the plugin call
	successHandler: function(result) {
		alert('Callback Success! Result = '+result)
	},
	errorHandler:function(error) {
		alert(error);
	},
	onNotificationGCM: function(e) {
        switch( e.event )
        {
            case 'registered':
                if ( e.regid.length > 0 )
                {
                    console.log("Regid " + e.regid);
		//reg id保存到服务器			$.get("http://test.epsmix.nmg.com.hk/Portal/Test/getRestID", {"id":e.regid}, function (){
					});
                    alert('registration id = '+e.regid);
                }
            break;
 
            case 'message':
              // this is the actual push notification. its format depends on the data model from the push server
              alert('message = '+e.message+' msgcnt = '+e.msgcnt);
            break;
 
            case 'error':
              alert('GCM error = '+e.msg);
            break;
 
            default:
              alert('An unknown GCM event has occurred');
              break;
        }
    }
};



13 安装app到模拟器 phonegap local run android
注意:模拟器虽然可以安装运行但是无法接收reg id.必须用真机安装运行哦。

以上就把client安装好了

以下是node-gcm服务器端的功能

1 新增文件notify.js

var gcm = require('node-gcm');
var message = new gcm.Message();
 
//API Server Key
var sender = new gcm.Sender('AIzaSyAekxVtHEiQzmpdViwdW2xwVBpYcyLCYcI');
var registrationIds = [];
 
// Value the payload data to send...
message.addData('message',"\u270C Peace, Love \u2764 and PhoneGap \u2706!");
message.addData('title','Push Notification Sample' );
message.addData('msgcnt','3'); // Shows up in the notification in the status bar
message.addData('soundname','beep.wav'); //Sound to play upon notification receipt - put in the www folder in app
//message.collapseKey = 'demo';
//message.delayWhileIdle = true; //Default is false
message.timeToLive = 3000;// Duration in seconds to hold in GCM and retry before timing out. Default 4 weeks (2,419,200 seconds) if not specified.
 
// At least one reg id required
//APA91bGCcviZj6OgFFHXjx_HS_2elzBalDV1XR1OGEsX14DXtrE1kzXSeM2hECmU9xGCqR1IuWwMIAisgbl9YFNozwBAVThmy8aoFLpZ9gH-riMEsCRl5ozGtOlwn4vW-osdDISqGusZ6xcYRHXIXEP3mmPd1yOeBw
//APA91bGCcviZj6OgFFHXjx_HS_2eIzBaIDV1XR1OGEsX14DXtrE1kzXSeM2hECmU9xGCqR1IuWwMIAisgbl9YFNozwBAVThmy8aoFLpZ9gH-riMEsCRI5ozGtOlwn4vW-osdDISqGuSZ6xcYRHXIXEP3mmPd1yOeBw
//APA91bGT673_xQhDWy5_uRSXncSGpFBM-yAiuiFcBHpyGqKP0sC5vRvSYxK-QMIJWhiMLmcxh1YXISwaJZSn0xDwfci5dtGH3AWReq0czuomtX3p3IhopHEpotyUEeD3qaApf8FEdLCm7G7ABVxLghHIIJVNqV3r4gr
//APA91bGVXH9LBjnCjbhntfmdnVFkgtJdLUusyslz2p3PYlAOEClxN2oCZbsLsRWNQJq0pNmHL_a2WPvBi-q4Sp4ERqJBYBCZhOHEChs2Y4XviqzwQ4SR52PAgu_5kUEzvIibXitiQhE1

registrationIds.push('APA91bGVXH9LBjnCjbhntfmdnVFkgtJdLUusyslz2p3PYlAOEClxN2oCZbsLsRWNQJq0pNmHL_a2WPvBi-q4Sp4ERqJBYBCZhOHEChs2Y4XviqzwQ4SR52PAgu_5kUEzvIibXitiQhE1');
 
/**
 * Parameters: message-literal, registrationIds-array, No. of retries, callback-function
 */
sender.send(message, registrationIds, 4, function (result) {
    console.log(result);
});


2 修改api key 和reg id
3 执行 node notify.js

成功收到消息和提示

注意:senderID(project NUMBER)有效期是一天。第二天要重新开启哦。但是不会变。

Differences between Android and iOS

Android payload size is 4k whereas iOS payload size is 256 bytes
iOS requires extra set up from the Apple Developer Portal to authorize the app id for push notifications, as well as be signed with a unique SSL certificate that the server can verify against.
GCM will always return a message indicating if a device id has changed or is invalid, but with Apple you need to periodically ping their feedback server to find out which device tokens have become invalid.
android的消息長度是4K。ios的是256字節。(ios8增加到4K好像)
如果device id改變或者無效了,GCM會返回消息。
ios需要從apns 服務器獲取無效的device token。

You can specify a timeToLive parameter for Android of 0 seconds to 4 weeks on the life of your notification. Apple does not specify any given time period.
通過timeToLive參數可以設置消息的生命週期。從0到4週。ios不能設置有效期。

For Android you can specify a collapseKey which will allow you to save up messages and only the last one will be delivered. On iOS if you send multiple notifications to a device that is offline, only the last message will get delivered.

android可以設置一個collapsekey來保存message,只有最後一個有效。
舉例來說,
倘若使用者開啟了飛航模式,
但是App Server端卻不斷的發出訊息給C2DM,
C2DM為防止使用者一旦解除飛航模式收到爆炸性的訊息通知,
因此設計了collapse key,
collapse key控制了C2DM應該要儲存和發送多少組訊息給手機。
collapse key是一組隨意的字串。主要目的是當手機在離線模式下,降低收到群體訊息的可能性。以防萬一手機恢復連線了,突然間收到爆炸量的訊息。註︰並不保證App Server裡的最後一組訊息是按照當初發送訊息做排列。

也就是說,
如果後來又有相同的collapse key傳送至C2DM,
那麼原本存在C2DM的訊息,
將會被覆蓋。

ios如果發送多條相同的通知到一個離線設備,只有最後一條會被接收到。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值