In this tutorial you will implement push notifications in your PhoneGap application. You will learn the following:
- An overview of the push notification handling process
- How to use the PushPlugin supported by PhoneGap Build
- An overview of the PushPlugin APIs
- How to register your application to receive push notifications
- How to use a simple node service to send a push notification to your registered device
- Differences between Android and iOS for handling push notifications
Overview
Android devices receive push notifications through the Google Cloud Messaging (GCM) service, whereas iOS devices receive them from the Apple Push Notifications (APN) Service. Though there are differences in the two services in terms of the size of the payload that can be sent, certificates required etc, both act as a store and forward type of service where they receive a message from a 3rd party, identify the recipient and pass it along. Upon receipt, your application that has registered to receive them can examine the returned contents and act accordingly. The way the notifications are received (by sound, alert etc) is a combination of the options set in the application code upon registration as well as the user’s device settings for notifications.
Getting Started
There is an official plugin called PushPlugin available to use for push notifications support and it’s supported by PhoneGap Build. This is the plugin used in the tutorial. The source code for a working project for PhoneGap Build (PhoneGap version prior to 3.0) can be found on my github account here. If you’re working with PhoneGap version 3.0 or greater, a complete working project for that version can be found here.
This tutorial does not go into depth about creating accounts on Google Cloud Messaging or the details behind setting up your application with the Apple Developer Portal but see the following articles on those topics.
I will be focusing mainly on Android and the Google Cloud Messaging service in this tutorial. However, see these two posts below on using push notifications for iOS:
Android Pre-requisites
- Google Cloud Messaging Project ID
- Google Cloud Messaging API Key for above Project ID (need for server)
iOS Pre-requisites
- App ID configured for Push Notifications on Apple Developer Portal
- SSL Certificate and private key (need for server)
Part 1: Configure your app to use the PushPlugin
In this part we’re going to add support for the PushPlugin to our application.
***Plugin Installation with the PhoneGap CLI (Command Line Interface)
- Create a basic PhoneGap project
$ phonegap create PushNotificationSample --id "com.pushapp" --name "PushNotificationApp"
- cd into the newly created project folder
$ cd PushNotificationSample
- Build the application for Android (also adds it as a platform under the /platforms folder)
$ phonegap local build android
- Install the PushPlugin from its github location via the PhoneGap CLI:
$ phonegap local plugin add https://github.com/phonegap-build/PushPlugin
- Locate the PushNotification.js file that was installed into your project-root/plugins folder. This file must be copied into your project-root/www folder and referenced from the index.html currently. The file should exist under in a location such as mine:
../PushNotificationSample/plugins/com.phonegap.plugins.PushPlugin/www/PushNotification.js
- Add the following script line to your index.html to reference the PushNotification.js.
1
<
script
type
=
"text/javascript"
src
=
"PushNotification.js"
></
script
>
Now you’re ready to start adding code and can skip to Part 2!
***Plugin Installation for PhoneGap Build
For PhoneGap Build you’ll need to refer to the plugin in the www/config.xml file in the project root and specify the script tag for the PushNotifications.js file and PhoneGap Build will inject it for us at build time. These steps are shown below:
- Add the following script line to your index.html to reference the PushNotification plugin.
1
<
script
type
=
"text/javascript"
src
=
"PushNotification.js"
></
script
>
- Add the following line to the www/config.xml file so PhoneGap Build will know to inject the Push Plugin code:
1
<
gap:plugin
name
=
"com.adobe.plugins.pushplugin"
/>
Part 2: Register the application with the Google Cloud Messaging service
In this step we will register our application with the Google Cloud Messaging service to receive push notifications.
Start by creating an account and project with the GCM service here. Once your project is created, it will be assigned a project id. You can see that id in the GCM console but it’s also appended to the URL such as this: https://code.google.com/apis/console/#project:824841663931. Make note of it as you will need it for the registration call.
- Open your base application in your editor and navigate to the www/js/index.js file. In the receivedEvent function, add the following code to get a reference to the push notification plugin object and call the register function. You will need to pass in a success and error callback function and then a couple of parameters including the project id you were assigned when you set up your project with Google Cloud Messaging as the senderID and a callback function for any messages received from GCM as the ecb parameter:
12
var
pushNotification = window.plugins.pushNotification;
pushNotification.register(app.successHandler, app.errorHandler,{
"senderID"
:
"824841663931"
,
"ecb"
:
"app.onNotificationGCM"
});
- Next code each of the callback functions referred to in the above registration call:
- Start with adding the successHandler which will be called when the registration is successful. The result will contain the registration token and we are displaying it in an alert:
1234
// result contains any message sent from the plugin call
successHandler:
function
(result) {
alert(
'Callback Success! Result = '
+result)
},
- Next add the errorHandler to be called if an error is returned from the registration request. In this handler we’ll simply display an alert showing the error received:
123
errorHandler:
function
(error) {
alert(error);
},
- And finally add the callback function to be called when messages are received from GCM to the end of your index.js file before the closing bracket. In my case I’ve named it onNotificationGCM as we may go back and add support for iOS push notifications to the same application and would need a different callback in that case. The function checks for the event received and handles simply displays an alert showing the contents.
12345678910111213141516171819202122232425
onNotificationGCM:
function
(e) {
switch
( e.event )
{
case
'registered'
:
if
( e.regid.length > 0 )
{
console.log(
"Regid "
+ e.regid);
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
;
}
}
Run your application
You have a few options you can choose to run your application…
- Run locally with CLI
You can run your application on your local device using the PhoneGap CLI with the following command from your terminal window from somewhere inside your project root:
$ phonegap local run android
- Run remotely with CLI
You can send your application to be built on PhoneGap Build and receive the QR code on the command line to run it from by using the following:
$ phonegap remote run android
- Run with PhoneGap Build
Log in to PhoneGap Build and upload your project zip to PhoneGap Build or specify its’ git location and build through the web interface. Scan the QR code or download the resulting package to your device.
When you run the application you should see a call made to register your android device and a token received in an alert such as shown below:
So now our application is ready to receive push notifications from the Google Cloud Messaging service. We can test out sending a message using some simple JavaScript with nodejs. There’s a library called node-gcm that we can use to send push notifications to GCM. We’ll just need the token or registration id that was returned from our call to register with GCM, as well as a server API key from GCM that’s associated with our project. You create this key in the GCM console for your project id under the API Access menu. Click Create new Server key…
- Install the node-gcm module. This library handles the communication with the Google Cloud Messaging server and gives you helpful classes to make it easy to send a message.
- Go to your GCM console and locate the Server API key (click the API Access link in the menu on the left to locate they keys). If you haven’t created one already you will need to do so now.
- Get the registration id returned to our application from the console. I like to use the Android adb tool so I can run logcat to watch the console while my application is running. Assuming you have the android-sdk tools and platform-tools set on your environment path you can simply run
adb logcat
from the command line to show your device log. - Open your editor and create a file called notify.js and paste in the following, replacing the Sender key and device registration id with yours.
12345678910111213141516171819202122232425
var
gcm = require(
'node-gcm'
);
var
message =
new
gcm.Message();
//API Server Key
var
sender =
new
gcm.Sender(
'AIzaSyCDx8v9R0fMsAsjoAffF-P3FCFWXlvwLhg'
);
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
registrationIds.push(
'APA91bwu-47V0L7xB55zoVd47zOJahUgBFFuxDiUBjLAUdpuWwEcLd3FvbcNTPKTSnDZwjN384qTyfWW2KAJJW7ArZ-QVPExnxWK91Pc-uTzFdFaJ3URK470WmTl5R1zL0Vloru1B-AfHO6QFFg47O4Cnv6yBOWEFcvZlHDBY8YaDc4UeKUe7ao'
);
/**
* Parameters: message-literal, registrationIds-array, No. of retries, callback-function
*/
sender.send(message, registrationIds, 4,
function
(result) {
console.log(result);
});
- Now type the following from the command line where the script was created to run the code and send a push notification:
node notify.js
You should hear the notification and see it in your status bar like this on your Android device (varies by device model):
When clicked on, the application should open and you should see this alert popup showing the message data:
Other Things to Note…
- You can set the badge number from the PushPlugin API via:
1
pushNotification.setApplicationIconBadgeNumber(
this
.successHandler, 0);
- You can specify a custom sound to play by including the sound file in your www folder and referring to it from the server side.
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.
- 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.
- 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.
Summary
Now that you know how you can receive push notifications, the next step would be to save the registration id’s or device tokens from all of the devices that are running your application so you can access them from the server-side when you need to send a notification for your application. You would also of course add and any specific handling code needed when certain notifications are received.
原地址: http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
- Start with adding the successHandler which will be called when the registration is successful. The result will contain the registration token and we are displaying it in an alert: