I need to send a JSON containing the category and the message all users who have my application installed, like this:
{category:"shoes", message:"New pair of shoes available"}
then I need to display a alert/notification only to users which checked a specific option which matches the category in the JSON.
I'm using Ionic, NodeJS and Express. How could I do that?
Hello Shadow00,
Then first of all you have to install FOUR Plugins for that.
1)cordova plugin add https://github.com/phonegap-build/PushPlugin
// For notification
2)cordova plugin add cordova-plugin-device
// For on Device Ready to call
3)cordova plugin add cordova-plugin-dialogs
// For notification Dialog
4)cordova plugin add cordova-plugin-media
// For Notification Sound
and generate API key and SenderId throw developer console.and senderid past in bellow code. And e.regid pass to on server.
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript">
var pushNotification;
function onDeviceReady() {
$("#app-status-ul").append('<li>deviceready event received</li>');
document.addEventListener("backbutton", function(e)
{
$("#app-status-ul").append('<li>backbutton event received</li>');
if( $("#home").length > 0)
{
// call this to get a new token each time. don't call it to reuse existing token.
//pushNotification.unregister(successHandler, errorHandler);
e.preventDefault();
navigator.app.exitApp();
}
else
{
navigator.app.backHistory();
}
}, false);
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"661780372179","ecb":"onNotification"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if (e.alert) {
$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if (e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for 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 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 payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/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>');
//android only
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
//amazon-fireos only
$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + 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;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// 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.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
<div id="home">
<div id="app-status-div">
<ul id="app-status-ul">
<li>Cordova PushNotification Plugin Demo</li>
</ul>
</div>
</div>
Related
I am trying to get a RegistrationID from the GCM service.
All i can see in Logcat is an empty string: "registrationId = null".
Does the Project name of the Google API have to match the apps name?
The documentation says:
For example, an Android app is identified by the package name from the manifest. This ensures that the messages are targeted to the correct Android app.
I do not exactly understand which names are being compared to each other...
My code is based on this PushPlugin example:
var pushNotification;
function onDeviceReady() {
$("#app-status-ul").append('<li>deviceready event received</li>');
document.addEventListener("backbutton", function(e)
{
$("#app-status-ul").append('<li>backbutton event received</li>');
if( $("#home").length > 0)
{
// call this to get a new token each time. don't call it to reuse existing token.
//pushNotification.unregister(successHandler, errorHandler);
e.preventDefault();
navigator.app.exitApp();
}
else
{
navigator.app.backHistory();
}
}, false);
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"960122754475","ecb":"onNotification"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if (e.alert) {
$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if (e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for 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 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 payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/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>');
//android only
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
//amazon-fireos only
$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + 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;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// 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.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
document.addEventListener('deviceready', onDeviceReady, true);
SOLVED:
It´s a problem of the android emulator.
Since Testing it on a real device, everything works fine.
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" - https://github.com/phonegap-build/PushPlugin
I believe that this problem looks like this question:
Cordova Push Plugin: onNotificationGMC is not fired and cannot obtain regID
But I'm using Ionic Framework. I follow this tutorial in making PushProcessingService:
http://intown.biz/2014/04/11/android-notifications/
//factory for processing push notifications.
angular.module('starter.pusher', [])
.factory('PushProcessingService', function(MyService) {
function onDeviceReady() {
console.info('NOTIFY Device is ready. Registering with GCM server');
alert('NOTIFY Device is ready. Registering with GCM server');
//register with google GCM server
var pushNotification = window.plugins.pushNotification;
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'myappid', 'ecb': 'onNotificationGCM'});
}
function gcmSuccessHandler(result) {
console.info('NOTIFY pushNotification.register succeeded. Result = ' + result);
alert('NOTIFY pushNotification.register succeeded. Result = ' + result)
}
function gcmErrorHandler(error) {
console.error('NOTIFY ' + error);
}
return {
initialize: function() {
console.info('NOTIFY initializing');
document.addEventListener('deviceready', onDeviceReady, false);
},
registerID: function(regid) {
//Insert code here to store the user's ID on your notification server.
//You'll probably have a web service (wrapped in an Angular service of course) set up for this.
//For example:
MyService.registerNotificationID(regid).then(function(response) {
if (response.data.Result) {
console.info('NOTIFY Registration succeeded');
} else {
console.error('NOTIFY Registration failed');
}
});
},
//unregister can be called from a settings area.
unregister: function() {
console.info('unregister')
var push = window.plugins.pushNotification;
if (push) {
push.unregister(function() {
console.info('unregister success')
});
}
}
}
});
// ALL GCM notifications come through here.
function onNotificationGCM(e) {
console.log('EVENT -> RECEIVED:' + e.event + '');
alert('EVENT -> RECEIVED:' + e.event + '');
switch (e.event)
{
case 'registered':
if (e.regid.length > 0)
{
console.log('REGISTERED with GCM Server -> REGID:' + e.regid + '');
alert(e.regid);
//call back to web service in Angular.
//This works for me because in my code I have a factory called
// PushProcessingService with method registerID
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var myService = injector.get('PushProcessingService');
myService.registerID(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)
{
//we're using the app when a message is received.
console.log('--INLINE NOTIFICATION--' + '');
// if the notification contains a soundname, play it.
//var my_media = new Media('/android_asset/www/'+e.soundname);
//my_media.play();
alert(e.payload.message);
}
else
{
// otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart)
console.log('--COLDSTART NOTIFICATION--' + '');
else
console.log('--BACKGROUND NOTIFICATION--' + '');
// direct user here:
window.location = '#/tab/dash';
}
console.log('MESSAGE -> MSG: ' + e.payload.message + '');
console.log('MESSAGE: ' + JSON.stringify(e.payload));
break;
case 'error':
console.log('ERROR -> MSG:' + e.msg + '');
alert('ERROR -> MSG:' + e.msg + '');
break;
default:
console.log('EVENT -> Unknown, an event was received and we do not know what it is');
alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}
But the onNotificationGCM(e) callback seems not to be working. I've moved it inside the factory, but the problem persists. I call the function in my app.js:
app.run(function($ionicPlatform, PushProcessingService) {
try {
PushProcessingService.initialize();
} catch (err) {
alert(err);
}
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
Please help me on solving this. Because I've been stuck for few days. Thank you!! :)
are device ready function getting called? are you adding device ready listener?
do like this:
document.addListener("deviceready" function(){
var pushNotification = window.plugins.pushNotification;
pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'myappid', 'ecb': 'onNotificationGCM'});
}
function gcmSuccessHandler(result) {
console.info('NOTIFY pushNotification.register succeeded. Result = ' + result);
alert('NOTIFY pushNotification.register succeeded. Result = ' + result)
}
function gcmErrorHandler(error) {
console.error('NOTIFY ' + error);
}
});
I finally try to use ngCordova Push Notification plugin as described here:
http://ngcordova.com/docs/plugins/pushNotifications/
Everything works well.
To be noted: The plugin won't work in browser nor emulator. It works only in real device, in my case, Android device.
I hope this helps people who face the same problem as I had.
I'm trying to register my Android device and obtain a registration ID so I can send push notifications to my app.
I have followed the steps listed here and have registered my app.
http://developer.android.com/google/gcm/gs.html
I have a Project ID and a Project Number, along with an API key and have turned on Google Cloud Messaging for Android.
I am using PhoneGap Build to develop my app and using the following plugin for my Push Notifications.
https://github.com/phonegap-build/PushPlugin/blob/1979d97/README.md
I have installed the plugin in my config.xml file using
<gap:plugin name="com.phonegap.plugins.pushplugin" version="2.4.0" />
Along with it's supporting plugins:
<gap:plugin name="org.apache.cordova.media" />
<gap:plugin name="org.apache.cordova.device" />
I've followed the instructions and examples and have developed this code for registering my device:
var pushNotification;
function onDeviceReady() {
alert('Device is ready')
try
{
pushNotification = window.plugins.pushNotification;
//$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
alert('Registering ' + device.platform);
if(device.platform == 'android' || device.platform == 'Android' ||device.platform == 'amazon-fireos' ) {
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"XXXXXXXXXX",
"ecb":"onNotification"
}); // required!
alert('Registered the Android device');
alert('regID = ' + e.regid);
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
alert('Registered the iOS device');
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
//alert(txt);
alert('Error: ' + err.message);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if(e.alert) {
//$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
//alert('push-notification: ' + e.alert);
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if(e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if(e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android
function onNotification(e) {
//$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
alert('EVENT -> RECEIVED:' + e.event);
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);
alert(' 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>');
alert('--INLINE NOTIFICATION--');
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/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>');
alert('--COLDSTART NOTIFICATION--')
else
//$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
alert('--BACKGROUND NOTIFICATION--')
}
//$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
alert('MESSAGE -> MSG: ' + e.payload.message);
//android only
//$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
alert('MESSAGE -> MSGCNT: ' + e.payload.msgcnt);
//amazon-fireos only
//$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp + '</li>');
alert('MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp);
break;
case 'error':
//$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
alert('ERROR -> MSG' + e.msg);
break;
default:
//$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}
function tokenHandler (result) {
//$("#app-status-ul").append('<li>token: '+ result +'</li>');
// 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('iOS Result = ' + result);
}
function successHandler (result) {
//$("#app-status-ul").append('<li>success:'+ result +'</li>');
alert('Android Result = ' + result);
alert('RegID = ' + e.regid);
}
function errorHandler (error) {
//$("#app-status-ul").append('<li>error:'+ error +'</li>');
alert('Error = ' + error);
}
document.addEventListener('deviceready', onDeviceReady, true);
alert('regID = ' + e.regid);
alert('Reg code completed');
My result returns "OK", but my regID returns "undefined", any suggestions into why or how to fix this would be very much appreciated.
I had the same issue like this and figure out the solution. I hope it helps.
var pushNotification;
function successHandler (result) {
}
function errorHandler (error) {
}
window.onNotificationGCM = function(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log('REGISTERED -> REGID:' + e.regid );
}
break;
case 'message':
console.log('gcm: on message ');
break;
case 'error':
console.log( "gcm error: "+e.msg );
break;
default:
break;
}
};
function initialize() {
document.addEventListener("deviceready", function(){
console.log("device ready");
pushNotification = window.plugins.pushNotification;
if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){
try {
pushNotification.register(
successHandler, errorHandler, { "senderID":"562539000000", "ecb":"window.onNotificationGCM" });
} catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
});
}
Did you test your push notification in your emulator or a physical device? If you tested in your emulator, you might have regID "undefined".
You can also refer to this issue in the PushPlugin GitHub.
Using Phonegap Build to use a push notifications requests for Android devices, when doing registration the request and see what's happened!
var pushNotification=window.plugins.pushNotification;
var return = pushNotification.register(successHandler , errorHandler,{"senderID":GCMProject,"ecb":"onNotification"});
function successHandler (result) {
alert('result = ' + result); // returned 'result = ok' //
}
function errorHandler (error) {
alert('error = ' + error);
}
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 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 payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
var my_media = new Media("/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>');
break;
case 'error':
$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
break;
default:
alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}
The successHandler() is fired with ('ok') message result!
Why the onNotification() method is not fired any time???
The application is not deployed on Play Store yet. It is used locally but connected to the internet.
Thank you for your suggestions.
The problem was with the JS Library, when we put the code directly into index.js, it works properly. So the problem wa included into the object define in the PushNotification.js script.
I used the example source code from (https://github.com/phonegap-build/PushPlugin/tree/master/Example/www). Problem is that, when I install my app and launch it my android phone (or android SDK emulator), it fails to register device to Android GCM. All the time error pops-up - "Device is not defined". I dont know exactly how I can catch error, why it fails to register device.
Steps that I preformed is:
– Created Phonegap project
– Installed following 3 plugins (cordova-plugin-device.git, cordova-plugin-media.git, PushPlugin).
– Registered App in Google Android GCM and retrieved my Goolge cloud API and Project Number
Locate the PushNotification.js file that was installed into my project-root/plugins folder. This file was copied into my project-root/www folder and referenced from the index.html
Added in my index file
Added to my www/config.xml file
Added JQuery mobile JS + CSS files to my project
Changed senderID in my HTML code:"1111146417746
Builded app with CLI - phonegap build android
And here is my Index.html code:
<html>
<head>
<title>com.PhoneGap.c2dm</title>
</head>
<body>
<!--<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>-->
<link rel="stylesheet" href="ext/jquery/jquery.mobile-min.css">
<script type="text/javascript" src="ext/jquery/jquery-min.js"></script>
<script type="text/javascript" src="ext/jquery/jquery.mobile-min.js"></script>
<script type="text/javascript" src="ext/jquery.qrcode.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript">
var pushNotification;
function onDeviceReady() {
$("#app-status-ul").append('<li>deviceready event received</li>');
document.addEventListener("backbutton", function(e)
{
$("#app-status-ul").append('<li>backbutton event received</li>');
if( $("#home").length > 0)
{
// call this to get a new token each time. don't call it to reuse existing token.
//pushNotification.unregister(successHandler, errorHandler);
e.preventDefault();
navigator.app.exitApp();
}
else
{
navigator.app.backHistory();
}
}, false);
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"111111117746","ecb":"onNotification"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if (e.alert) {
$("#app-status-ul").append('<li>push-notification: ' + e.alert + '</li>');
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if (e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if (e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for 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 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 payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/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>');
//android only
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
//amazon-fireos only
$("#app-status-ul").append('<li>MESSAGE -> TIMESTAMP: ' + 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;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// 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.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
document.addEventListener('deviceready', onDeviceReady, true);
</script>
<div id="home">
<div id="app-status-div">
<ul id="app-status-ul">
<li>Cordova PushNotification Plugin Demo</li>
</ul>
</div>
</div>
</body>
</html>
Go to your plugins folder and check whether you have a folder named cordova-plugin-device.
That plugin should be installed in your project. So if that folder is missing you need to install it by opening your terminal and going to the root of your project to execute the following command
cordova plugin add cordova-plugin-device
This should add the plugin.
Found a solution for this myself. As it turned out, these two JS files:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
had to been moved in HEAD section, not inside BODY section. Then it works fine!
Put your registration code under DeviceReady function
var platform = null;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
platform = device.platform;
//alert(platform);
$("#app-status-ul").append('<li>'+ platform +'</li>');
try
{
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
if (device.platform == 'android' || device.platform == 'Android' ||
device.platform == 'amazon-fireos' ) {
pushNotification.register(successHandler, errorHandler, {"senderID":"860557673192","ecb":"onNotification"}); // required!
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
}