Important - Push notifications are intended for real devices. They are not tested for WP8 Emulator. The registration process will fail on the iOS simulator. Notifications can be made to work on the Android Emulator, however doing so requires installation of some helper libraries, as outlined here, under the section titled "Installing helper libraries and setting up the Emulator".

Contents

The MIT License
Copyright (c) 2012 Adobe Systems, inc.
portions Copyright (c) 2012 Olivier Louvignes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Create a new text file called ant.properties in the platforms/amazon-fireos folder, and add a java.compiler.classpath entry pointing at the library. For example: java.compiler.classpath=./ext_libs/amazon-device-messaging-1.0.1.jar

Modify res/xml/config.xml to set config options to let Cordova know whether to display ADM message in the notification center or not. If not, provide the default message. By default, message will be visible in the notification. These config options are used if message arrives and app is not in the foreground (either killed or running in the background).

Add the PushNotification.js script to your assets/www folder (or javascripts folder, wherever you want really) and reference it in your main index.html file. This file's usage is described in the Plugin API section below.

Note: For each service supported - ADM, APNS, GCM or MPNS - you may need to download the SDK and other support files. See the Manual Installation instructions below for more details about each platform.

Cordova

The plugin can be installed via the Cordova command line interface:

Navigate to the root folder for your phonegap project. 2) Run the command.

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

Phonegap

The plugin can be installed using the Phonegap command line interface:

Navigate to the root folder for your phonegap project. 2) Run the command.

On success, you will get a call to tokenHandler (iOS), onNotification (Android and Amazon Fire OS), onNotificationWP8 (WP8) or successHandler (Blackberry10), allowing you to obtain the device token or registration ID, or push channel name and Uri respectively. Those values will typically get posted to your intermediary push server so it knows who it can send notifications to.

Note

Amazon Fire OS: "ecb" MUST be provided in order to get callback notifications. If you have not already registered with Amazon developer portal,you will have to obtain credentials and api_key for your app. This is described more in detail in the Registering your app for Amazon Device Messaging (ADM) section below.

Android: If you have not already done so, you'll need to set up a Google API project, to generate your senderID. Follow these steps to do so. This is described more fully in the Testing section below. In this example, be sure and substitute your own senderID. Get your senderID by signing into to your google dashboard. The senderID is found at Overview->Dashboard->Project Number.

BlackBerry10: "ecb" MUST be provided to get notified of incoming push notifications. Also note, if doing a public consumer (BIS) push, you need to manually add the _sys_use_consumer_push permission to config.xml. <rim:permit system="true">_sys_use_consumer_push</rim:permit>. In order to receieve notifications, an invoke target must be setup for push. See BlackBerry Push Service for additional information about blackberry push options.

// Android and Amazon Fire OSfunctiononNotification(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 payloadvar soundfile =e.soundname||e.payload.sound;
// if the notification contains a soundname, play it.var my_media =newMedia("/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;
}
}

// BlackBerry10functionpushNotificationHandler(pushpayload) {
var contentType =pushpayload.headers["Content-Type"],
id =pushpayload.id,
data =pushpayload.data;//blob// If an acknowledgement of the push is required (that is, the push was sent as a confirmed push// - which is equivalent terminology to the push being sent with application level reliability),// then you must either accept the push or reject the pushif (pushpayload.isAcknowledgeRequired) {
// In our sample, we always accept the push, but situations might arise where an application// might want to reject the push (for example, after looking at the headers that came with the push// or the data of the push, we might decide that the push received did not match what we expected// and so we might want to reject it)pushpayload.acknowledge(true);
}
};

Looking at the above message handling code for Android/Amazon Fire OS, a few things bear explanation. Your app may receive a notification while it is active (INLINE). If you background the app by hitting the Home button on your device, you may later receive a status bar notification. Selecting that notification from the status will bring your app to the front and allow you to process the notification (BACKGROUND). Finally, should you completely exit the app by hitting the back button from the home page, you may still receive a notification. Touching that notification in the notification tray will relaunch your app and allow you to process the notification (COLDSTART). In this case the coldstart flag will be set on the incoming event. You can look at the foreground flag on the event to determine whether you are processing a background or an in-line notification. You may choose, for example to play a sound or show a dialog only for inline or coldstart notifications since the user has already been alerted via the status bar.

For Amazon Fire OS, offline message can also be received when app is launched via carousel or by tapping on app icon from apps. In either case once app delivers the offline message to JS, notification will be cleared.

Since the Android and Amazon Fire OS notification data models are much more flexible than that of iOS, there may be additional elements beyond message. You can access those elements and any additional ones via the payload element. This means that if your data model should change in the future, there will be no need to change and recompile the plugin.

senderID (Android only)

tokenHandler (iOS only)

Called when the device has registered with a unique device token.

functiontokenHandler (result) {
// Your iOS push server needs to know the token before it can push to this device// here is where you might want to send it the token for later use.alert('device token = '+ result);
}

setApplicationIconBadgeNumber (iOS only)

The badgeCount is an integer indicating what number should show up in the badge. Passing 0 will clear the badge.

unregister (Amazon Fire OS, Android and iOS)

You will typically call this when your app is exiting, to cleanup any used resources. Its not strictly necessary to call it, and indeed it may be desireable to NOT call it if you are debugging your intermediarry push server. When you call unregister(), the current token for a particular device will get invalidated, and the next call to register() will return a new token. If you do NOT call unregister(), the last token will remain in effect until it is invalidated for some reason at the GCM/ADM side. Since such invalidations are beyond your control, its recommended that, in a production environment, that you have a matching unregister() call, for every call to register(), and that your server updates the devices' records each time.

uccb (WP8 only)

Event callback that gets called when the channel you have opened gets its Uri updated. This function is needed in case the MPNS updates the opened channel Uri. This function will take care of showing updated Uri.

errcb (WP8 only)

Event callback that gets called when server error occurs when receiving notification from the MPNS server (for example invalid format of the notification).

Or you can add another Page2.xaml just for testing toast navigate url. Like the MSDN Toast Sample

To test the tile notification, you will need to add tile images like the MSDN Tile Sample

unregister (WP8 Only)

When using the plugin for wp8 you will need to unregister the push channel you have register in case you would want to open another one. You need to know the name of the channel you have opened in order to close it. Please keep in mind that one application can have only one opened channel at time and in order to open another you will have to close any already opened channel.

You'll probably want to trap on the backbutton event and only call this when the home page is showing. Remember, the back button on android is not the same as the Home button. When you hit the back button from the home page, your activity gets dismissed. Here is an example of how to trap the backbutton event;

windows

Sample usage is showed below. Note. To be able to receive toast notifications additional toastCapable=’true’ attribute is required in manifest file. Cordova-windows 4.0.0 release adds this property to config.xml. You can use:
<preference name="WindowsToastCapable" value="true" /> in config.xml. However, you will need Cordova 5.1.1 which pins Cordova-windows 4.0.0.

This plugin and its target Cordova application comprise the client application.The ADM, APNS, GCM and MPNS infrastructure are maintained by Amazon, Apple, Google and Microsoft, respectively. In order to send push notifications to your users, you would typically run an intermediary server or employ a 3rd party push service. This is true for all ADM (Amazon), APNS (iOS), GCM (Android) and MPNS (WP8) notifications. However, when testing the notification client applications, it may be desirable to be able to push notifications directly from your desktop, without having to design and build those server's first. There are a number of solutions out there to allow you to push from a desktop machine, sans server.

Testing APNS and GCM notifications

An easy solution to test APNS and GCM is a ruby gem called pushmeup (tested only on Mac, but it probably works fine on Windows as well).

Prerequisites:

Ruby gems is installed and working.

You have successfully built a client with this plugin, on both iOS and Android and have installed them on a device.

Android/GCM Setup

Go the this plugin's Example/server folder and open pushGCM.rb in the text editor of your choice.

Set the GCM.key variable to the API key you just generated.

Set the destination variable to the Registration ID of the device. (you can run the Cordova app / plugin in on a device via Eclipse and extract the regID from the log messages)

Sending a test notification

cd to the directory containing the two .rb files we just edited.

Run the Cordova app / plugin on both the Android and iOS devices you used to obtain the regID / device token, respectively.

$ ruby pushGCM.rb or $ ruby pushAPNS.rb

If you run this demo using the emulator you will not receive notifications from GCM. You need to run it on an actual device to receive messages or install the proper libraries on your emulator (You can follow this guide under the section titled "Installing helper libraries and setting up the Emulator") If everything seems right and you are not receiving a registration id response back from Google, try uninstalling and reinstalling your app. That has worked for some devs out there.

While the data model for iOS is somewhat fixed, it should be noted that GCM is far more flexible. The Android implementation in this plugin, for example, assumes the incoming message will contain a 'message' and a 'msgcnt' node. This is reflected in both the plugin (see GCMIntentService.java) as well as in provided example ruby script (pushGCM.rb). Should you employ a commercial service, their data model may differ. As mentioned earlier, this is where you will want to take a look at the payload element of the message event. In addition to the cannonical message and msgcnt elements, any additional elements in the incoming JSON object will be accessible here, obviating the need to edit and recompile the plugin. Many thanks to Tobias Hößl for this functionality!

Sending a test notification

Inside the plugin's examples/server folder, open the pushADM.js NodeJS script with a text editor. (You should already have NodeJS installed).

Edit the CLIENT_ID and CLIENT_SECRET variables with the values from the ADM Security Profile page for your app. This will allow your app to securely identify itself to Amazon services.

Compile and run the sample app on your device. Note the sample app requires the Cordova Device and Media plugins to work.

The sample app will display your device's registration ID. Copy that value (it's very long) from your device into pushADM.js, entered in the REGISTRATION_IDS array. To test sending messages to more than one device, you can enter in multiple REGISTRATION_IDS into the array.

To send a test push notification, run the test script via a command line using NodeJS: $ node pushADM.js.

Testing MPNS Notification for WP8

The simplest way to test the plugin is to create an ASP.NET webpage that sends different notifications by using the URI that is returned when the push channel is created on the device.

Sending push notifications on BlackBerry10

If doing a BES push, ensure the device has been enterprise activated, has network access (wifi or sim) and your app is installed in the work permiter. You also need to make sure the _sys_use_consumer_push permission is NOT specified in the config.xml. This permission is meant only for public consumer BIS pushes and will cause an error when registering.

If doing a public consumer BIS push, please ensure the _sys_use_consumer_push permission is added to the config.xml.

Troubleshooting and next steps

If all went well, you should see a notification show up on each device. If not, make sure you are not being blocked by a firewall, and that you have internet access. Check and recheck the token id, the registration ID and the certificate generating process.

In a production environment, your app, upon registration, would send the device id (iOS) or the registration id (Android/Amazon), to your intermediary push server. For iOS, the push certificate would also be stored there, and would be used to authenticate push requests to the APNS server. When a push request is processed, this information is then used to target specific apps running on individual devices.

If you're not up to building and maintaining your own intermediary push server, there are a number of commercial push services out there which support both APNS and GCM.