titanium studio push notifications closing the app - android

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)

Related

Ionic push notifications with Capacitor, registering and getting token but not receiving notifications Android

I have an Ionic 5 app with Capacitor 3 and I'm trying to receive notifications using Firebase Cloud messaging, on an Android device. I followed the configurations,(I downloaded the google JSON file and put my app id name correctly ) and I'm getting correctly the device token. Once my app is open I get the token successfully without any error and then I send a notification sharing my token to the Firebase test message, the notification never arrived, and also I never get an error of push notification in my logger. This is the code that I use for push notification.
export class PushNotificationsService {
constructor(private readonly http: HttpClient, private notificationState: NotificationsStore) { }
public initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermissions().then(async result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
console.log('granted');
await PushNotifications.register();
} else {
// Show some error
console.log('errorr');
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => { (I get through this step and access the token successfully)
console.log('Push registration success, token: ' + token.value);
this.notification state.setToken(token.value);
}
);
// I never get this step error
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
}
);
}
I also have capacitor.config.json like this:
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
Also, I checked that my device and app have permission for notifications and are enabled both. I tried and test this issue with my app open and closed and open only in the background and the notification never arrives. What it could be? Any clue? Thank you
Android Phone Please Create the channel Like this, Test or Add screenshot for console Error
if (Capacitor.getPlatform() === 'android') {
PushNotifications.createChannel({
id: 'fcm_default_channel',
name: 'app name',
description: 'Show the notification if the app is open on your device',
importance: 5,
visibility: 1,
lights: true,
vibration: true,
});
}

Appcelerator/ Titanium: Cannot send push notification to 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

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

Titanium Push notification "events" is not working (android)

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();

Categories

Resources