Appcelerator/ Titanium: Cannot send push notification to Android - android

I want to be able to send push notifications using Titanium and Arrow Push on Android.
I have followed the instructions here:
Configuring Push Services
Subscribing to push notifications
Modules.CloudPush
My simple code looks as follows:
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
// Works fine
CloudPush.retrieveDeviceToken({
success: function () {
deviceToken = e.deviceToken;
alert('deviceToken: ' + deviceToken);
subscribeToChannel();
},
error: function () {
alert('Failed to register for push notifications! ' + e.error);
}
});
// Never runs!!!
CloudPush.addEventListener('callback', function (evt) {
Ti.API.info('New notification!');
alert("Notification received: " + evt.payload);
});
// Works fine
function subscribeToChannel () {
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'general',
type: Ti.Platform.name
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
Most of the above code is similar to the docs. The subscription aspect of the code seems to works perfectly fine, as the user's device also appears in the devices section of the Appcelerator Dashboard.
However when it comes to sending a notification, from the Appcelerator Dashboard, the word "Failure" appears next to my Android device.
The full error message when highlighting the "?" icon is as follows:
Exception Type: GCM; Error Code: 3103; Error Message:
RegistrationId(s) is null or empty; Catched Exception: argument cannot
be null
I looked this error up on http://docs.appcelerator.com/arrowdb/latest/#!/guide/troubleshooting and all it says is:
The GCM client provided a null or empty registration ID. This error is
uncommon if you are using the Modules.CloudPush module.
Which isn't helpful.
What am I doing wrong? Is this a bug on Accelerator side.

Turns out my code was fine. The credentials I was using however was incorrect. Please see my other related question here:
Appcelerator/ Titanium: Getting Android credentials to push notifications
The docs are in need of updating.

I'm hardly an expert with push, but I compared what you have to what I have in one of my apps.
Pretty sure you need to send the deviceToken into the subscribeToChannel function.
Try changing this -
function subscribeToChannel () {
to this -
function subscribeToChannel (deviceToken) {
then add the token to the call here -
subscribeToChannel (deviceToken);
Let me know if that works for you.
-Jon

On subscribeToChannel() function, you should use type : 'gcm' instead of type: Ti.Platform.name
This is a commonJS module that I created for my Android push:
function ACSPush(_callback) {
var debug_mode = true;
var Cloud = require('ti.cloud');
var CloudPush = require('ti.cloudpush');
CloudPush.enabled = true;
var deviceToken;
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
if(debug_mode)
Ti.API.info('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
if(Ti.App.Properties.getString("deviceToken") != deviceToken.toString()){
defaultSubscribe();
};
},
error : function deviceTokenError(e) {
if(debug_mode)
Ti.API.info('deviceTokenError.. :( ' + e.error);
}
});
function defaultSubscribe() {
Cloud.PushNotifications.subscribeToken({
channel : 'MyChannel',
device_token : deviceToken,
type : 'gcm'
}, function(e) {
if(e.success) {
if(debug_mode)
Ti.API.info("Success registerForPushNotifications");
Ti.App.Properties.setString("deviceToken", deviceToken.toString());
} else {
if(debug_mode)
Ti.API.info('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
};
});
};
CloudPush.addEventListener('callback', function(evt) {
var payload = JSON.parse(evt.payload);
if(debug_mode){
Ti.API.info("Received a push notification\nPayload:\n" + JSON.stringify(evt.payload));
Ti.API.info("payload: " + payload);
};
_callback(payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
if(debug_mode)
Ti.API.info('Tray Click Focused App (app was already running)');
});
};
module.exports = ACSPush;
Obviously, you must first configure Android Push Service http://docs.appcelerator.com/platform/latest/#!/guide/Configuring_push_services-section-src-37551713_Configuringpushservices-ConfiguringpushservicesforAndroiddevices

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

FireBase push notification using cordova

I am trying to implement Firbase push notification using cordova. I use the code for the latest fcm plug in specificaion from here : Cordova Push Plugin
I can get the register token. Then I tried to send notification from Firebase test notification module using that token. Each time I run the app in my device I am having the alert-
"Msg: onNotification callback successfully registered: OK"
it is inside the second function of FCMPlugin.onNotification event.
But the first function [where I want to get the notification] is not called.
I don't find where I am making mistake. Here is my code inside onDeviceReady:
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
var parentElement = document.getElementById('deviceready');
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
//=========================
FCMPlugin.getToken(
function (token) {
alert("Token: " + token);
cordova.plugins.email.open({
to: 'sharif#nascenia.com',
subject: 'Greetings',
body: token
});
},
function (err) {
alert("Error: " + 'error retrieving token: ' + err);
}
);
FCMPlugin.onNotification(
function (data) {
alert("Notify: " + JSON.stringify(data));
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert("Wrapped Notify: " + JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert("Notify: " + JSON.stringify(data));
}
},
function (msg) {
alert("Msg: " + 'onNotification callback successfully registered: ' + msg.Notification);
},
function (err) {
alert("Error: " + 'Error registering onNotification callback: ' + err);
}
);
};
Make sure you add "click_action":"FCM_PLUGIN_ACTIVITY" to the payload for the REST API. This must be present for Android. If this isn't available you will NOT receive data from a tapped notification (or hear a sound).
See the REST API payload example from the cordova-plugin-fcm documentation:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY", // <<<<<<< Must be present for Android
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"/topics/topicExample",
"priority":"high",
"restricted_package_name":""
}
You are missing to subscribe to your topic before onNotification function like this :
FCMPlugin.subscribeToTopic('topic');

Titanium Alloy Push Notification Subscribed But Listener Not firing Up

I need to make a push notification listener, My code for this is below and it runs perfect till the subscription and the dashboard confirms it is subscribed successfully, but the problem occurs with the receiver.
Alloy.Globals.ServiceAddress = "my service address";
Ti.API.info("1");
var CloudPush = require('ti.cloudpush');
var Cloud = require("ti.cloud");
var deviceToken = null;
loginUser(); // flow starts from here
function loginUser() {
Cloud.Users.login({
login: 'User',
password: 'Password'
}, function(e) {
if (e.success) {
var user = e.users[0];
// alert("Loggin successfully");
getDeviceToken();
} else {
alert("Error2*** :" + e.message);
//Ti.API.info('error ')
}
});
}
function getDeviceToken() {
if (Ti.Platform.Android) {
CloudPush.debug = true;
CloudPush.focusAppOnPush = false;
CloudPush.enabled = true;
CloudPush.showAppOnTrayClick = true;
CloudPush.showTrayNotification = true;
CloudPush.singleCallback = true;
CloudPush.singleCallback = true;
CloudPush.retrieveDeviceToken({
success: deviceTokenSuccess,
error: deviceTokenError
});
}
}
// Enable push notifications for this device
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
alert(e.deviceToken);
subscribeToChannel(deviceToken);
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Process incoming push notifications
function subscribeToChannel(deviceToken) {
// Subscribes the device to the 'news_alerts' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'Vision', //'You_App',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function(e) {
if (e.success) {
alert('Subscribed');
SendNotification(deviceToken);
} else {
// indicator.visible = false;
alert('Subscribe Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function SendNotification(to_deviceToken) {
alert('sendnot');
Cloud.PushNotifications.notifyTokens({
channel: 'My Cannel',
to_tokens: to_deviceToken,
payload: 'Welcome to push notifications'
}, function(e) {
if (e.success) {
alert('Success Send');
} else {
alert('Send Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}
When I add event-listener to push notifications it doesn't even fire up however, the client is saying it is connected.
<!-- language: lang-js -->
CloudPush.addEventListener('callback', function (evt) {
alert('rec');
alert("Notification received: " + evt.payload);
});
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)');
});
PS. I have searched and already read related threads Like this one
I am attaching the log to make it clarify that subscription and notification send is working properly
Push notification Log
and
Connected Clients
Solved
I was compiling with titanium api level 4.1.1.v20151203143424 with CloudPush module version 3.2.1
I migrated to titanium 6.0.0.v20160202173231 with cloudpush module version 3.4.1
and all set see in this pic

Ionic Framework PushPlugin: onNotificationGMC is not fired and cannot obtain regID

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.

titanium studio push notifications closing the app

I am trying to show push notifications in android app, developed by titanium studio, my getting alert with unfortunately app is closed after this my is clossing, my code is
try {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
deviceID = e.deviceToken;
Ti.API.info(deviceID);
Ti.App.Properties.setString('deviceid', '' + deviceID);
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
} catch(e) {
alert('Error :', e);
}
// Enable push notifications for this device
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
CloudPush.enabled = true;
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Process incoming push notifications
CloudPush.addEventListener('callback', function(evt) {
//alert(evt.payload);
var alertNotification = Titanium.UI.createAlertDialog({
title : 'app',
message : evt.data.alert,
cancel : 1,
buttonNames : ['OK']
});
alertNotification.show();
});
// Triggered when the push notifications is in the tray when the app is not running
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
});
// Triggered when the push notifications is in the tray when the app is running
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
});
what was the wrong I am doing will any one suggest me, how to resolve this isssue
thanks in advace
Try changing your code as follows
var CloudPush = require('ti.cloudpush');
try {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
deviceID = e.deviceToken;
CloudPush.enabled = true;
Ti.API.info(deviceID);
Ti.App.Properties.setString('deviceid', '' + deviceID);
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
} catch(e) {
alert('Error :' + e);
}
// Process incoming push notifications
CloudPush.addEventListener('callback', function(evt) {
//alert(evt.payload);
var alertNotification = Titanium.UI.createAlertDialog({
title : 'app',
message : evt.data.alert,
cancel : 1,
buttonNames : ['OK']
});
alertNotification.show();
});
// Triggered when the push notifications is in the tray when the app is not running
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
});
// Triggered when the push notifications is in the tray when the app is running
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
});
I have removed the callback methods from your code.
And also please make sure that you're using the latest CloudPush module. Please check the TiApp.xml, if you have selected '*' as module version, change it to latest number (3.2.3 for me)

Categories

Resources