I'm trying to test a Push Notification app with Phonegap. I registered my project at GCM and added my Project Number at the SenderID var. Here's the code:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
receivedEvent: function(id) {
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);
var pushNotification = window.plugins.pushNotification;
alert("Register called");
pushNotification.register(this.successHandler, this.errorHandler,{"senderID":"543180841340","ecb":"app.onNotificationGCM"});
},
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);
alert('registration id = '+e.regid);
document.getElementById('regId').value = e.regid;
}
break;
case 'message':
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;
}
},
onNotificationAPN: function(event) {
var pushNotification = window.plugins.pushNotification;
alert("Running in JS - onNotificationAPN - Received a notification! " + event.alert);
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.badge) {
pushNotification.setApplicationIconBadgeNumber(this.successHandler, this.errorHandler, event.badge);
}
if (event.sound) {
var snd = new Media(event.sound);
snd.play();
}
}
};
I get the first alert ("Register called") but not the regID. I'm using the Phonegap Developer app for Android and the "phonegap serve" command to get it live. I tried to download the app too, but still doesn't work.
Firing the ("Register called") Doesn't mean that the push notification registration is instantiated but it means that receivedEvent is called and that is good.
1- Make sure that push notification plugin is included in config.xml and the pushNotification object is not null.
to include the plugin to config.xml: add <gap:plugin name="com.phonegap.plugins.pushplugin" />
2- Make sure that the sender id is OK "no typos".
Related
I am using Google Chrome Push Notification in my site.
Currently I have more than 1,00,000 subscribed users.
I'm facing this following issue.
- My users started using the notifications.
- I need to change the logic of the service-worker but could not able update it.
- I have not given any cache based installation with my previous Service-Wroker.js
- I have not used any fetch event with the previous Service-Worker.js
Changes done in new Service-Worker.js
- Landing URL (clickUrl) variable is added into the self.addEventListener function
My Existing Service-Wroker.js
'use strict';
var port;
var pushMessage;
var clickUrl;
var imgUrl;
self.addEventListener('push', function(event) {
var obj = event.data;
pushMessage = event.data ? event.data.text() : '';
var pushData = pushMessage.split('####');
clickUrl = pushData[2];
imgUrl = pushData[1];
if (port) {
port.postMessage(pushMessage);
}
event.waitUntil(self.registration.showNotification(pushData[3], {
requireInteraction: true,
body: pushData[0],
icon: pushData[1]
}));
});
self.addEventListener('notificationclick', function(event) {
if (Notification.prototype.hasOwnProperty('data')) {
event.notification.close();
event.waitUntil(clients.openWindow(clickUrl));
}
});
self.onmessage = function(e) {
port = e.ports[0];
if (pushMessage) {
port.postMessage(pushMessage);
}
};
The new / updated Service-Worker.js [Changes I need to update / implement]
'use strict';
var port;
var pushMessage;
var clickUrl;
var imgUrl;
self.addEventListener('push', function(event) {
var obj = event.data;
pushMessage = event.data ? event.data.text() : '';
var pushData = pushMessage.split('####');
clickUrl = pushData[2];
imgUrl = pushData[1];
if (port) {
port.postMessage(pushMessage);
}
event.waitUntil(self.registration.showNotification(pushData[3], {
requireInteraction: true,
body: pushData[0],
icon: pushData[1],
data:{
url : clickUrl
}
}));
});
self.addEventListener('notificationclick', function(event) {
var landingUrl = event.notification.data.url;
if (Notification.prototype.hasOwnProperty('data')) {
event.notification.close();
event.waitUntil(clients.openWindow(landingUrl));
}
});
self.onmessage = function(e) {
port = e.ports[0];
if (pushMessage) {
port.postMessage(pushMessage);
}
};
self.addEventListener('install', function(event) {
console.log('[ServiceWorker] Installed version', version);
event.waitUntil(
caches.open('my-cache').then(function(cache) {
// Important to `return` the promise here to have `skipWaiting()`
// fire after the cache has been updated.
return cache.addAll([/* file1.jpg, file2.png, ... */]);
}).then(function() {
// `skipWaiting()` forces the waiting ServiceWorker to become the
// active ServiceWorker, triggering the `onactivate` event.
// Together with `Clients.claim()` this allows a worker to take effect
// immediately in the client(s).
return self.skipWaiting();
})
);
});
// Activate event
// Be sure to call self.clients.claim()
self.addEventListener('activate', function(event) {
// `claim()` sets this worker as the active worker for all clients that
// match the workers scope and triggers an `oncontrollerchange` event for
// the clients.
return self.clients.claim();
});
An update is triggered:
On navigation to an in-scope page.
On functional events such as push and sync, unless there's been an update check within the previous 24 hours.
On calling .register() only if the service worker URL has changed.
more here https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle
I am new to cordova and plugins..
I have created a webappp, in my app i need to download files from server..
so i have used cordova background download plugin.. and i m using intel xdk.. so i have impoted plugin there..
cordova plugin github
now.. when i download file, on notification bar its showing downloading file.. BUT ITS SHOWING PLUGIN PACKAGE NAME WHILE DOWNLOADING.... but file save as its original name.... here it is my code..
var app = {
fileName: "tera hone.mp3",
uriString: "https://api.soundcloud.com/tracks/133667943/stream?client_id=67739332564a7130c3a05f90f2d02d2e", // 38.3 MB
// Application Constructor
initialize: function() {
this.bindEvents();
},
downloadFile: function(uriString, targetFile) {
var lblProgress = document.getElementById('lblProgress');
var complete = function() {
lblProgress.innerHTML = 'Done';
};
var error = function (err) {
console.log('Error: ' + err);
lblProgress.innerHTML = 'Error: ' + err;
};
var progress = function(progress) {
lblProgress.innerHTML = (100 * progress.bytesReceived / progress.totalBytesToReceive) + '%';
};
try{
var downloader = new BackgroundTransfer.BackgroundDownloader();
// Create a new download operation.
var download = downloader.createDownload(uriString, targetFile);
// Start the download and persist the promise to be able to cancel the download.
app.downloadPromise = download.startAsync().then(complete, error, progress);
} catch(err) {
console.log('Error: ' + err);
}
},
// 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);
document.getElementById('btnStart').addEventListener('click', this.startDownload);
document.getElementById('btnStop').addEventListener('click', this.stopDownload);
document.getElementById('btnFileInfo').addEventListener('click', this.getFileInfo);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
app.startDownload();
},
startDownload: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (newFile) {
app.downloadFile(app.uriString, newFile);
});
});
},
stopDownload: function () {
app.downloadPromise && app.downloadPromise.cancel();
},
getFileInfo: function () {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(app.fileName, { create: true }, function (fileEntry) {
fileEntry.file(function (meta) {
document.getElementById('lblFileInfo').innerHTML =
"Modified: " + meta.lastModifiedDate + "<br/>" +
"size: " + meta.size;
});
}, function(error) {
document.getElementById('lblFileInfo').innerHTML = "error: " + error;
});
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
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);
}
};
this is my javascript file invoke from my html file.. from cordova plugin..
also when i stop downloading.. it stops but app suddenly crashed everytime....
sorry for my bad english..
I am building my app using phonegap.I have Write a Code for on double click of back button of phone app should be close but its not working i have write a code.
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready',onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
var exitApp = false, intval = setInterval(function () { exitApp = false; }, 1000);
document.addEventListener("backbutton", function (e) {
e.preventDefault();
if (exitApp) {
clearInterval(intval)
(navigator.app && navigator.app.exitApp()) || (device && device.exitApp())
}
else {
exitApp = true
history.back();
}
}, false);
},
receivedEvent: function(id) {
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);
}
};
so whats is Problem in it because it is act as its default back going functionality. i am using phone gap version 3.7.0.
#vatsal,
double click on the screen is the default for zoom. Using the back button that way is not a good way to exit. Most people use a dedicate [exit] button. You might consider the same.
FWIW, you do NOT need the e.preventDefault(); for that event.
You can look at my notes and source code on events here:
https://github.com/jessemonroy650/Phonegap-Events-test
and here:
https://github.com/jessemonroy650/Phonegap-PhysicalButton-test/blob/master/NOTES
Jesse
I'm using this plugin to see if my phone has internet connection:
https://github.com/apache/cordova-plugin-network-information
But not working.. show me this error:
D/CordovaLog( 3169): file:///android_asset/www/index.html: Line 44 : Uncaught TypeError: Cannot read property 'connection' of undefined
My function :
````
var App = {
//Application Constructor
init: function() {
this.bindEvents();
},
//Bind Event Listeners
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
//Event Handle
onDeviceReady: function() {
//Fast click
FastClick.attach(document.body);
Usuario.verificarOnline();
DataBase.init();
alert(App._internet());
},
getUrl: function(){
return App.url;
},
//verificar conexao com internet
_internet: function(){
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = false;
states[Connection.ETHERNET] = true;
states[Connection.WIFI] = true;
states[Connection.CELL_2G] = true;
states[Connection.CELL_3G] = true;
states[Connection.CELL_4G] = true;
states[Connection.CELL] = true;
states[Connection.NONE] = false;
return states[networkState];
}
};
````
Either it means you didn't install the plugin :
cordova plugin add cordova-plugin-network-information
or it means you didn't wait for the device to be ready before calling your function:
document.addEventListener('deviceready', function()
{
// Call the function
}
I am using cordova push notification plugin un my angular application. I have created this service for the notifications:
define(["app"], function (app) {
'use strict';
var pushNotificationService = function ($q, localStorageService) {
var registrationDefered;
function registrationSuccess(result) {
}
function registrationError(error) {
}
function test(notificationData) {
localStorageService.set('notification_url', notificationData.url);
}
function isOnBrowser() {
var result = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
return !result;
}
//Android Amazon callback
app.onNotificationGCM = function(e) {
console.log(e);
switch(e.event) {
case 'registered':
if (e.regid.length > 0) {
// 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.
var data = {
registrationID: e.regid,
device: device.platform.toLocaleLowerCase()
};
registrationDefered.resolve(data);
}
break;
case 'message':
test(e.payload);
// 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) {
console.log(e);
// 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>');
}
}
break;
case 'error':
break;
default:
break;
}
};
//public
var serviceApi = {
register: function() {
var pushNotification = window.plugins.pushNotification;
registrationDefered = $q.defer();
debugger;
if(device.platform.toLocaleLowerCase() == 'android' || device.platform == "amazon-fireos") {
pushNotification.register(
registrationSuccess,
registrationError,
{
"senderID": "238062858076",
"ecb":"angular.module('App').onNotificationGCM"
}
);
} else if(isOnBrowser()) {
var data = {
registrationId: "",
device: "browser"
};
registrationDefered.resolve(data);
}
/* else if (device.platform == 'blackberry10'){
pushNotification.register(
registrationSuccess,
registrationError,
{
invokeTargetId : "replace_with_invoke_target_id",
appId: "replace_with_app_id",
ppgUrl:"replace_with_ppg_url", //remove for BES pushes
ecb: "pushNotificationHandler",
simChangeCallback: replace_with_simChange_callback,
pushTransportReadyCallback: replace_with_pushTransportReady_callback,
launchApplicationOnPush: true
});
} else {
pushNotification.register(
tokenHandler,
errorHandler,
{
"badge":"true",
"sound":"true",
"alert":"true",
"ecb":"onNotificationAPN"
});
}*/
return registrationDefered.promise;
}
};
//public
return {
register: serviceApi.register
}
};
return pushNotificationService;
});
Now, I am able to register (I am getting the registration ID) but when the device receives a notification it seems that the application not running the js logic written in the callback function under the message case: test(e.payload).
Note that I'm am receiving the notification butlocalStorageService.set('notification_url', notificationData.url); is never being set to the provided value.
Can you please help me to understand why it is not running? is it even suppose to run (if the application is not running - installed but not running)
The thing is that I made the registration only on login. Now I have added this line to my module run callback:
app.run(function() {
pushNotificationService.register().then(function(result) {
console.log(result); //this just for debugging
});
});