I added push notification "events" but is not working.
I dont understand. Error can not be given and Log in is not working.
please help me. Thanks
my gcm module
var gcm = require("nl.vanvianen.android.gcm");
var CloudPush = require('ti.cloudpush');
/* If the app is started or resumed act on pending data saved when the notification was received */
var lastData = gcm.getLastData();
if (lastData) {
Ti.API.info("Last notification received " + JSON.stringify(lastData));
gcm.clearLastData();
}
gcm.registerPush({
senderId : '480608162759',
notificationSettings : {
sound : 'mysound.mp3',
smallIcon : 'notification_icon.png',
largeIcon : 'appicon.png',
vibrate : true
},
success : function(event) {
Ti.API.info("Push registration success: " + JSON.stringify(event));
},
error : function(event) {
Ti.API.info("Push registration error = " + JSON.stringify(event));
alert(event.error);
},
callback : function(event) {
Ti.API.info("Push callback = " + JSON.stringify(event));
var dialog = Ti.UI.createAlertDialog({
title : 'Push received',
message : JSON.stringify(event.data)
// buttonNames: ['View'],
// cancel: 1
});
dialog.addEventListener("click", function(event) {
dialog.hide();
if (event.index == 0) {
/* Do stuff to view the notification */
}
});
dialog.show();
},
});
//Dont work eventlistener
CloudPush.addEventListener('callback', function(evt) {
console.log("Notification received: " + evt.payload);
});
Related
I am very new to Cordova and also I am using Urban Airship Push notification concept. I have a requirement like I have to get the Push notification in foreground also. But I am getting the notification in the background only. I am not getting the notification in foreground.
Here is my code :
function initPush(){
//alert("Push initialize");
console.log("Device ready!");
var status = localStorage.getItem("pushEnable")
if(status == null){
UAirship.setUserNotificationsEnabled(true);
}else{
if (localStorage.getItem("pushEnable") == "true") {
// alert("SET USER NOTFICAION ENABLE ");
UAirship.setUserNotificationsEnabled(true);
} else {
// alert("SET USER NOTFICAION DISBALE ");
UAirship.setUserNotificationsEnabled(false)
}
}
localStorage.setItem("uuid", device.uuid);
//alert("DEVICE ID ==>"+device.uuid);
var onRegistration = function(event) {
// alert("ON REGISTRAION CALLED");
window.plugins.spinnerDialog.show(null,"loading....", true);
if (!event.error) {
window.plugins.spinnerDialog.hide();
// alert("ON REGISTRAION SUCESS");
console.log("Reg Success:---> " + event.channelID)
// alert("ON REGISTRAION EVENT "+ JSON.stringify(event));
var uuid = localStorage.getItem("uuid")
localStorage.setItem("channelId", event.channelID)
var deviceInfo = {
channel_id: event.channelID,
device_id: uuid
};
UAirship.setNamedUser(uuid, function() {
//setNamedUser(uuid)
//alert("SETNAME SUCESS");
})
}else{
window.plugins.spinnerDialog.hide();
// alert("ON REGISTRAION FAILED");
}
}
//alert(device.serial)
var onPushReceived = function(event) {
alert("ON PUSH RECEIVED CALL");
if (event.message) {
dialogAlert("Message From LockerRoom", event.message)
alert("Message From LockerRoom", event.message)
console.log("Received push: " + event.message)
} else {
console.log("No incoming message")
}
}
// Notification opened callback
var notificationOpened = function(event) {
if (event.message) {
console.log("Notification opened: " + event.message)
} else {
console.log("No incoming message")
}
}
// Deep link callback
var handleDeepLink = function(event) {
console.log("Deep link: " + event.deepLink)
}
// Register for any urban airship events
document.addEventListener("urbanairship.registration", onRegistration, false)
document.addEventListener("urbanairship.push", onPushReceived, false)
document.addEventListener("urbanairship.notification_opened", notificationOpened, false)
document.addEventListener("urbanairship.deep_link", handleDeepLink, false)
// Handle resume
document.addEventListener("resume", function() {
// alert("Device resume!")
UAirship.resetBadge()
// Reregister for urbanairship events if they were removed in pause event
document.addEventListener("urbanairship.registration", onRegistration, false)
document.addEventListener("urbanairship.push", onPushReceived, false)
}, false)
// Handle pause
document.addEventListener("pause", function() {
// alert("Device Pause!")
// Remove urbanairship events. Important on android to not receive push in the background.
document.removeEventListener("urbanairship.registration", onRegistration, false)
document.removeEventListener("urbanairship.push", onPushReceived, false)
}, false)
// Get the launch notification if its available.
//this.receivedEvent('deviceready');
}
function initiateUI() {
//alert("InitUI");
var struuid = localStorage.getItem("uuid")
$('#namedUser').text(struuid)
var setNamedUser = function(namedUser) {
document.getElementById("setNamedUserField").disabled = true;
var namedUser = $("#namedUser").val(struuid)
UAirship.setNamedUser(namedUser, function() {
setNamedUser(struuid)
})
$("#namedUser").text(namedUser)
}
// Vibrate and Sound is only available on Android
if (device.platform != "Android") {
$("#soundEnabledSection").hide()
$("#vibrateEnabledSection").hide()
}
UAirship.getNamedUser(function(namedUser) {
//alert("getNamedUser--->" + getNamedUser);
if (namedUser) {
console.log("Got namedUser: " + namedUser)
setNamedUser(namedUser)
}
})
// Update the interface with the current UA settings
//var isEnabled = localStorage.getItem("pushEnable");
UAirship.isUserNotificationsEnabled(function(isEnabled) {
// alert("isUserNotificationsEnabled **(* ---- ENTER " + isEnabled); //0 - false
if (localStorage.getItem("pushEnable") == null) {
$('#pushEnabled').val(isEnabled ? 'on' : 'off').change()
} else if (localStorage.getItem("pushEnable") == "true") {
$('#pushEnabled').val('on').change();
} else {
$('#pushEnabled').val('off').change();
}
})
// Set up change callbacks for the UI elements
$('#pushEnabled').change(function() {
var isEnabled = ($('#pushEnabled').val() == "on")
UAirship.setUserNotificationsEnabled(isEnabled) //TRUE FALSE
localStorage.setItem("pushEnable", isEnabled); // TRUE FALSE
})
}
I don’t know what mistake I have done here. Can anyone please help me to resolve this.
Thanks In advance.
Push notification from android by default gives as an alert when the app is in foreground. The onPushReceived event handler will be called directly. You might receive just an Dialog alert that you called and console messages will be print.
If you want it instead to show as a notification use "forceShow":"true" value while sending notification. Source this. (I am not sure about it working for urbanairship plugins, but pls try and let me know).
Anyway for cordova its simplified. You can use phonegap-push-plugin. See example here.
Registration id is giving but event is not triggered. I don't understand why?
Please Help me. I did not understand where wrong?
// Cloud module and Cloud module use
Titanium.UI.setBackgroundColor('#000');
var win = Ti.UI.createWindow({
backgroundColor : '#ccc',
title : 'Android Cloud Push Notification'
});
//CloudPush modules variables
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotification = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
//Device Token variables
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
//create button
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color : '#000',
height : 53,
width : 200,
top : 100,
});
//add button on win scene
win.add(submit);
//CloudPush retrieveDeviceToken function
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('======= Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
loginDefault();
},
error : function deviceTokenError(e) {
alert('======= Failed to register for push! ' + e.error);
}
});
});
//Cloud login
function loginDefault(e) {
// At first you need to create an user from the application dashboard
// Then login that email and password
Cloud.Users.login({
login : '===',
password : '==='
}, function(e) {
if (e.success) {
alert("========login success");
defaultSubscribe();
} else {
alert('Error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',
device_token : deviceToken,
type : 'android'
}, function(e) {
if (e.success) {
alert('====== Subscribed for Push Notification!');
} else {
alert('Error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
//Doesnt Work this events
CloudPush.addEventListener('callback', function(evt) {
console.log(evt);
console.log(evt.payload);
});
//Doesnt Work this events
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
console.log('Tray Click Launched App (app was not running)');
//alert('Tray Click Launched App (app was not running');
});
//Doesnt Work trayClickFocusedApp events
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
console.log('Tray Click Focused App (app was already running)');
//alert('Tray Click Focused App (app was already running)');
});
win.open();
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 have a problem with PushPlugin in android. Has been searching hours for solution, but still no success.
The ecb is not fired when I get a push notification.
It is fired successfully on register,but when i close the app and get a notification, then i open the app by tapping the notification, it is not called.
here is my code :
var Utility = {
registerPushNotification : function() {
if( typeof device != 'undefined' )
{
// checking if device token is exist
var deviceToken = dbUtil.getValue('deviceToken');
if(deviceToken==null)
{
if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){
window.plugins.pushNotification.register(
function(result) {
alert('result = ' + result);
},
function(error) {
alert('error = ' + error);
},
{
"senderID":'my_project_number',
"ecb":"Utility.onNotification"
}
);
} else if (device.platform == 'iOS'){
window.plugins.pushNotification.register(
function(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);
dbUtil.setValue('deviceToken', result);
// upload deviceToken to server
Utility.registerDevice(result,app.CONSTANTS.TYPE_APNS);
},
function(error) {
// alert('error = ' + error);
pageUtil.drawToast('error getting device token');
},
{
"badge":"true",
"sound":"true",
"alert":"true",
"ecb":"Utility.onNotificationAPN"
});
}
}
}
},
onNotificationAPN : function (event) {
if ( event.alert )
{
navigator.notification.alert(event.alert);
}
if ( event.sound )
{
var snd = new Media(event.sound);
snd.play();
}
if ( event.badge )
{
// window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
},
// Android and Amazon Fire OS
onNotification : function(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.
// alert(e.regid);
// console.log("regID = " + e.regid);
dbUtil.setValue('deviceToken', e.regid);
// upload deviceToken to server
Utility.registerDevice(e.regid,app.CONSTANTS.TYPE_GCM);
}
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 )
{
// 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();
alert(e.payload.message);
}
else
{
pageUtil.loadingFullPage(true,e.payload.message);
// 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':
{
alert('error getting google notification');
break;
}
default:
{
break;
}
}
},
.....
};
here is how i register, the ecb is called and i can get the regID :
Utility.registerPushNotification();
but the case where e.event = "message" is never called.
note:
window.plugins.pushNotification.register is only called once. Do I have to call register every app launch?
Try to put
Utility.registerPushNotification() inside your deviceready event.
I am building a mobile application for both android/Ios,For android,require a push notification using parse to deliver my message and to get my request. I got the device token for my android device and i can list my recipients but if i click on send button my message is not delivered.Here is my code that i have
var uuid=Ti.Platform.createUUID();
var deviceToken;
var CloudPush = require('ti.cloudpush');
//fetch device token
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
//alert('Device Token: ' + deviceToken);
Ti.API.info('Device Token: ' + e.deviceToken);
loginDefault();
/////////parse start///
var c = Titanium.Network.createHTTPClient();
c.setTimeout(25000);
c.onload = function(e) {
Ti.API.info("onload");
svar = JSON.parse(this.responseText);
Ti.API.info(svar);
Ti.API.info('params'+this.responseText);
};
c.onerror = function(e) {
Ti.API.info("on error");
alert(e);
};
c.open('POST', 'https://api.parse.com/1/installations');
c.setRequestHeader('X-Parse-Application-Id', 'bopIfF9m4JpkAxww9syYvLHVaCmE2go9WW7uHS1K');
c.setRequestHeader('X-Parse-REST-API-Key', 'NZLlV86V8ruxq5GdXRi2NrepQXhyiSmmoDHeZasH');
c.setRequestHeader('Content-Type', "application/json; charset=utf-8");
var params = {
"deviceType": "android",
"deviceToken": deviceToken,
"installationId":uuid,
"pushType":"gcm",
};
Ti.API.info('value is'+params);
c.send(JSON.stringify(params));
///parse end/////
},
error : function deviceTokenError(e) {
// alert('Failed to register for push! ' + e.error);
}
});
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var Cloud = require('ti.cloud');
Cloud.debug = true;
function loginDefault(e) {
//Create a Default User in Cloud Console, and login with same credential
Cloud.Users.login({
login : 'push1',
password : '12345'
},
function(e) {
if (e.success) {
// alert("Login success");
defaultSubscribe();
} else {
// alert('Login error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',//'alert' is channel name
device_token : deviceToken,
type : 'gcm' //here i am using gcm, it is recomended one
}, function(e) {
if (e.success) {
// alert('Subscribed for Push Notification!');
} else {
//alert('Subscrib error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function(evt) {
// alert(evt.payload);
// alert("ggg");
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('#### Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('#### Tray Click Focused App (app was already running)');
});
Change
c.setRequestHeader('Content-Type', "application/json; charset=utf-8");
to
c.setRequestHeader('Content-Type', "application/json");