I have received push notification using FCM plugin. when i m clicking on notifiation, app splash screen was open but i but open another screen. how can i do it? please help.
app.js
.run(function ($ionicPlatform, $rootScope, $state) {
$ionicPlatform.ready(function() {
if(window.cordova) {
FCMPlugin.onNotification(
function(data){
$rootScope.notificationData = data;
$rootScope.reciveMessage(data);
$state.reload();
if(data.wasTapped){
// $state.go('message', {id:data.pageId});
// $location.path('app/userList');
console.log('onNotification tapped true');
} else {
console.log("xxxxxxxxxxxx"+data.message);
}
},
function(msg){
// alert("asdf"+msg)
console.log('onNotification callback successfully registered: ' + msg);
FCMPlugin.getToken(
function(token){
//alert(token);
window.localStorage.setItem("deviceId",token)
},
function(err){
console.log('error retrieving token: ' + err);
}
)
},
function(err){
// alert("fjkjg"+err)
console.log('Error registering onNotification callback: ' + err);
}
);
}
});
})
Related
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
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');
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 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");
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)