Push notification in cordova - android

I am using cordova plugin add phonegap-plugin-push --variable SENDER_ID=XXXXXXXX
this plugin. And added following code into javascript file.
function setupPush() {
var push = PushNotification.init({
"android": {
"senderID": "XXXXXXXX"
},
"ios": {
"sound": true,
"alert": true,
"badge": true
},
"windows": {}
});
push.on('registration', function(data) {
console.log("registration event: " + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
}
It gives error as "TypeError: Cannot call method 'init' of undefined".

This usually happens if you haven't done this after onDeviceReady. You can't access any native device APIs until after this fires (push notifications, camera, etc).
function onDeviceReady() {
// Sets up your push notifications
setupPush();
}
// Fires when device is ready.
document.addEventListener("deviceready", onDeviceReady, false);

Related

Desperately need help for Firebase - Push Notifications

I’m trying to develop Firebase - Push Notifications with Framework7. I have installed the plugin by checking $ cordova plugin list
cordova-plugin-fcm 2.1.2 “FCMPlugin”
I have registered the app on the Firebase Console and have no idea whether this code is correct or not (it’s inside the app.js)
onDeviceReady: function() {
// JScript for the main app, once PGap has loaded.
//checkDeviceSize(); (WILL RE-CODE IN A CSS FRIENDLY FORMAT)
document.addEventListener(“offline”, onOffline, false);
document.addEventListener(“online”, onOnline, false);
setTimeout(function() {
navigator.splashscreen.hide();
}, 1000);
var pushtoken;
initFCM();
getToken();
},
then, at the bottom of file app.js, I put the function
function initFCM() {
console.log("initializing...");
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.onTokenRefresh(function(token){
pushtoken = token;
app.dialog.alert('onTokenRefresh:', token);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
FCMPlugin.onNotification(function(data){
if(data.wasTapped){
app.dialog.alert(JSON.stringify(data));
}else{
app.dialog.alert(JSON.stringify(data));
}
}, function(msg){
app.dialog.alert('onNotification callback successfully registered: ' + msg);
}, function(err){
app.dialog.alert('Error registering onNotification callback: ' + err);
});
}
}
function getToken() {
if(typeof(FCMPlugin) != 'undefined') {
FCMPlugin.getToken(function(token){
pushtoken = token;
app.dialog.alert('getToken:', token);
if (!token) setTimeout(getToken, 1000);
}, function(err){
app.dialog.alert('error retrieving token: ' + err);
});
}
}
Would be very grateful if you can show how to manage this code inside app.js
Many thanks

Getting error in telerik push notification for android

I am trying to implement push notification for my hybrid application using telerik platform. It is working fine for iOS. But in android, its getting an error - "Push notifications are currently initializing".
This is the code that I have used.
app.everlive = new Everlive({
appId: "xxxxxxx",
scheme: 'http'
});
var enablePushNotifications = function() {
var devicePushSettings = {
iOS: {
badge: 'true',
sound: 'true',
alert: 'true'
},
android: {
senderID: 'xxxxxxx'
},
wp8: {
channelName: 'EverlivePushChannel'
},
notificationCallbackIOS: onPushNotificationReceived,
notificationCallbackAndroid: onPushNotificationReceived,
notificationCallbackWP8: onPushNotificationReceived
};
app.everlive.push.currentDevice().enableNotifications(devicePushSettings, successCallback, errorCallback);
function onPushNotificationReceived(e) {
alert(JSON.stringify(e));
};
function successCallback(e) {
app.everlive.push.register(devicePushSettings, function() {
alert("Successful registration in Backend Services. You are ready to receive push notifications.");
}, function(err) {
alert("Error: " + err.message);
});
alert(JSON.stringify(e));
};
function errorCallback(e) {
alert(JSON.stringify(e));
};
};
Its going to errorCallback. Could any one please help me out with this? Thanks in advance.

Ionic push notifications on Android doesn't register token on Ionic.io

I want to implement push notification on Android using ionic.
I've followed the documentation from Ionic push in a tutorial from devdactic Devdactic push notifications android I see with that example in the platform is saved a token.
I've make all settings that I need including GCM service and register user to ionic platform, but no token is registered.
I run app in emulator and user is registered but no token is saved. After some modifiers I receive a token in console but is not ok.
In example token is different and push does't work. Does someone have an working example with Ionic Push based on last documentation?
this is what I use to register pushes, it is messy but hopefully can be of some use. It checks if the current user is authenticated, if they aren't then it signs them up with a UUID (i used a UUID generator plugin) and saves the token. Just make sure your app is set up with Ionic.io and this should work :)
var user = Ionic.User.current();
if (user.isAuthenticated()) {
var push = new Ionic.Push({
"debug": true,
"onNotification": function (notification) {
},
"onRegister": function (data) {
console.log(data.token);
return true;
},
"pluginConfig": {
"android": {
"icon": "icon"
},
"ios": {
"badge": true,
"sound": true,
"alert": true
}
}
});
} else {
var uid = uuid2.newuuid();
var details = {
'email': uid + '#example.com',
'password': 'secretpassword'
};
Ionic.Auth.signup(details).then(function () {
var options = { 'remember': true };
Ionic.Auth.login('basic', options, details).then(function () {
user = Ionic.User.current();
user.set('uid', uid);
user.save();
var push = new Ionic.Push({
"debug": true,
"onNotification": function (notification) {
},
"onRegister": function (data) {
console.log(data.token);
return true;
},
"pluginConfig": {
"android": {
"icon": "icon"
},
"ios": {
"badge": true,
"sound": true,
"alert": true
}
}
});
push.register(function (token) {
console.log("Device token:", token.token);
push.saveToken(token);
});
}, function () { });
}, function () { });
}
In order to send push notification you need Api key and project number and current device id.
I think you are struggling in getting the user device id in order to get the current your device id please reffer ng-Cordova
you can find a line
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification)
in this you can see the notification parameter it is an object inside that object you can find regid field in that you can get your current device id this will be work on only mobile not on browser.
so in order to use that device id, for example lets assume your going to post a login form with divece id like given below.
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
console.log(event);
console.log(notification);
switch(notification.event) {
case 'registered':
console.log(notification.regid.length);
if (notification.regid.length > 0 ) {
// alert('registration ID = ' + notification.regid);
console.log('registration ID = ' + notification.regid);
var loginPost = {
"UserName":username,
"PassWord":password,
"DeviceID":notification.regid
};
console.log(loginPost);

Custom sound using ionic push notifications

I am trying to implement custom sound for my push notifications in Ionic application.
I copied the sound file to www/ also set plugin options as follows
//In app.run
$ionicPush.init({
"debug": true,
"onNotification": function(notification){
$cordovaDialogs.alert(notification.message, 'Notification', 'OK').then(function(){
console.log(notification);
});
}
"onRegister": function(data) {
console.info("New device registered with token "+data.token);
}
"pluginConfig": {
"ios": {
"badge": true,
"sound": true
},
"android": {
"iconColor": "#343434"
}
}
});
//In my main controller -
$scope.saveUserDeviceReg = function(data){
var ionicUser = Ionic.User.current();
if(!ionicUser.id){
ionicUser.id = $scope.user.userId;
}
ionicUser.set('name', $scope.user.name);
ionicUser.set('image', $scope.user.profilePic);
ionicUser.set('email', $scope.user.email);
$ionicPush.addTokenToUser(ionicUser);
ionicUser.save();
if($scope.user.devices){
$scope.user.devices[data.token] = true;
$scope.user.$save().then(function(success){
console.log("User device saved");
},function(error){
console.error("Error saving user device");
});
}
else{
var devices = {};
devices[data.token] = true;
$scope.user.devices = devices;
$scope.user.$save().then(function(success){
console.log("User device updated");
},function(error){
console.error("Error updating user device");
});
}
};
​
$ionicPush.register($scope.saveUserDeviceReg);
I send the push notification from a node.js server
request({
url: "https://push.ionic.io/api/v1/push",
method: "POST",
json: true,
body: {
"tokens":tokens,
"notification": {
"alert": message.from + " : '" + message.text
}
},
headers: {
'Authorization': 'Basic ' + btoa(IONIC_PRIVATE_API_KEY + ":"),
'X-Ionic-Application-Id': IONIC_APP_ID
}
}, function (error, response, body) {
console.log(body);
});
I want to play a custom audio that is stored in www/.
With Cordova CLI 7 you can use resource-tag to copy the sounds to the projects http://cordova.apache.org/docs/en/7.x/config_ref/index.html#resource-file
For Android:
<resource-file src="sound.mp3" target="res/wav/sound.mp3" />
for iOS:
<resource-file src="sub.caf"/>
Old answer:
To play a custom sound, the sound file name has to be passed from the server on the push notification data
On iOS the sound file has to be on the app project, not on www
On android the sound file has to be on the res/raw folder, not on www
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#sound
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#sound-1

ionic framework parse push notifications device not registered

I'm trying to get parse push notifications to work on my android device. I have done the GCM setup and tested it with urbanairship. It works.
But for some reasons I need to get it to run with parse.
What I have done so fare...
in my $ionicPlatform.ready function I initialize the parse plugin like this:
window.parsePlugin.initialize(
"XXX",
"XXX",
function() {
alert( 'PARSE INIT OK' );
window.parsePlugin.getInstallationId(function(id) {
installationID = id;
}, function(e) {
console.log("Error Getting ID: " + e.code + " : " + e.message);
})
},
function( e ) {
alert( 'PARSE FAILED' );
});
});
In my HelloCordova.java files onCreate function I added this:
Parse.initialize(this, "XXX", "XXX");
PushService.setDefaultPushCallback(this, HelloCordova.class);
ParseAnalytics.trackAppOpened(getIntent());
ParseInstallation.getCurrentInstallation().saveInBackground();
I followed the Parse Android instructions to modify my AndroidManifest.xml.
And I added the parse and phonegap notification plugin to the project.
cordova plugin add https://github.com/avivais/phonegap-parse-plugin
But I can't register the device for Parse notification.
i also tried so many times on this. iOS did work but not android. but after i installed this plugin it worked.
https://github.com/avivais/phonegap-parse-plugin
Use this in app.js and it did work.
.run(function($ionicPlatform) {
$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();
}
try{
parsePlugin.initialize('xxx', 'yyy', function() {
alert('success');
}, function(e) {
alert('error');
});
}catch(err){
alert('Parse Error '+err.message); //this gets executed all time
}
});
})

Categories

Resources