How to read FCM playload inside mobile device? - android

I am creating mobile app in Cordova which receive notification and payload using cordova-plugin-firebase-messaging 7.0.4 "FirebaseMessagingPlugin" plugin to get device token successfully and send notification to specific device successfully.
What i have tried so far,in index.js file i added below code to get token,payload and badge.
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
cordova.plugins.firebase.messaging.getToken().then(function(token) {
alert(token);
document.getElementById('txtGCMId').value = token;
});
cordova.plugins.firebase.messaging.onMessage(function(payload) {
alert(payload);
});
cordova.plugins.firebase.messaging.onBackgroundMessage(function (payload) {
alert(payload);
});
cordova.plugins.firebase.messaging.getBadge().then(function(value) {
alert(value);
});
}
Using gettoken i can get token , but in onMessage() and onBackgroundMessage() i cant receive payload and also getBadge() i cant recive badge count which send in payload.
I am using Postman Agent to send notification using https://fcm.googleapis.com/fcm/send firebase rest api.
This is notification i send
{
"to": "e3PGidrDSqKP-pOHJ0W_yC:APA91bEGmKlVzYatnJam1GJ2k55fFJlMfT2uIymZnLQoFvYYoxBXKOMvaN26l1flFwDMbrQoLxWqCQEc0wWxIHRjEfUn7t13kzXPsFDXECsRVUTR1CLxynzg270H22jHaaqzJugFcGhS",
"notification": {
"body": "Testing from Sample",
"title": "Testing",
"icon": "myicon",
"sound": "default",
"badge": "10"
},
"data" : {
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
So how to receive payload and badge and show badge count in app icon.
Note: My Cordova version 11.0.0 and following plugin i installed,
cordova-plugin-firebase-messaging 7.0.4 "FirebaseMessagingPlugin"
cordova-support-android-plugin 2.0.4 "cordova-support-android-plugin"
Any reply much appreciated.
Regards,
Aravind

anything passed in the notification will appear as a notification. Anything passed in the data, you can display as below
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
cordova.plugins.firebase.messaging.getToken().then(function(token) {
alert(token);
document.getElementById('txtGCMId').value = token;
//why print the above line? why not save that on the server in a database?
});
cordova.plugins.firebase.messaging.onMessage(function(payload) {
alert(payload.key_1); //the value key_1, key_2 that you have set in your payload for the data array. this is the foreground payload action. When the app is open. You can either set a badge count or do what ever you want.
});
cordova.plugins.firebase.messaging.onBackgroundMessage(function (payload) {
alert(payload.key_1) // this is the background notification event. When the user clicks on the notification, you would want to take the user to a specific page or perform some action. any thing set in data array is called by payload.<data_param>
});
cordova.plugins.firebase.messaging.getBadge().then(function(value) {
alert(value);
});
}

Related

A phone call notification simulation using ionic framework

I want to send a push notification from server to an ionic client and show this notification in client like a phone call (mobile device should play a sound and show 'Accept' or 'Reject' buttons with caller information). It should work if mobile app is not running or in background, that's why I decided to use FCM messages.
this.storage.get('firebase_token').then((token) => {
console.log('Orders get firebase token and call register. Token: ' + token);
this.agentService.registerPushNotifications(token, () => {
this.firebase.onNotificationOpen().subscribe((notification) => {
// How to open the app and show the page with a ringtone ??
});
});
});
How can I open the app and show the call page with a ringtone in incoming push notification? Or maybe there is a better way for this kind of feature.
What you are asking for (the same format like a phone call) isn't possible with Ionic. You can however redirect the user to a view inside the application where you ask him to take action.
Take the following example for push notification. In app.components.ts I initialize this function when the platform is ready
initializePushNotifications() {
let pushObject = this.push.init({
android: {
senderID: 'Your ID Here',
icon: 'logo'
},
ios: {
alert: true,
badge: false,
sound: true
},
windows: {}
});
if (!pushObject['error']) {
pushObject.on('registration').subscribe((data: RegistrationEventResponse) => {
// Whatever you want to do
}, err => {
console.log('Couldnt register:', err);
})
pushObject.on('notification').subscribe((data: any) => {
let self = this;
// When the user click the push notification
if (!data.additionalData.foreground) {
switch (data.additionalData.entity_type) {
case 'takeAction':
this.openView(data.additionalData.user_name, data.additionalData.id);
break;
......
}
}
});
pushObject.on('error').subscribe((e: any) => {
console.log(e.message);
});
} else {
console.error(pushObject);
}
}
See, in the pushed message we add an object under the key additionalData where you can pass whatever you want. You can pass something like entity_type with the value takeAction. When the user click it, you can open a new view and pass additional parameters like the name of the user and the id of the entity or whatever.
On this screen you can open an alert asking the user to click yes or no and based on his input you fire the correct request.
Note
I know this is different from what you were asking for but your request cannot be fulfilled using Ionic.

addEventListener in ionic 3

I need to read sms on it arrive. I get cordova-plugin-sms and use this code. But how i could change this code in order to work in ionic 3?
if(window.SMS){
window.SMS.startWatch(data => {
console.log('watching', 'watching started');
}, error => {
console.log('failed to start watching');
});
}
document.addEventListener('onSMSArrive', function(e) {
var sms = e.data;
console.log(sms);
});
This plugin is not meant to read/receive/listen to SMS.
From the FAQ section of the repo:
How can I receive SMS?
You can't receive SMS via this plugin. This plugin only sends SMS.
There is a major difference between the plugins
cordova-sms-plugin and
cordova-plugin-sms
the last one supports receiving SMS, but not the first
There are some open issues with cordova-plugin-sms and Ionic 3 compatibility.
You can use an alternate plugin cordova-plugin-sms-receive
It has below code that you can use in your app for receiving sms:
Event: onSMSArrive
Triggered when a new SMS has arrived. You need call startWatch() first.
/* Initialize incoming SMS event listener */
document.addEventListener('onSMSArrive', function(e) {
console.log('onSMSArrive()');
var IncomingSMS = e.data;
console.log('sms.address:' + IncomingSMS.address);
console.log('sms.body:' + IncomingSMS.body);
/* Debug received SMS content (JSON) */
console.log(JSON.stringify(IncomingSMS));
});
try with following change-
if((<any>window).SMS){
(<any>window).SMS.startWatch(data => {
console.log('watching', 'watching started');
}, error => {
console.log('failed to start watching');
});
}
(<any>window).addEventListener('onSMSArrive', function(e) {
var sms = e.data;
console.log(sms);
});

Ionic v2 : Push notification to open specific page

I try to build an android App with push notification and I want to open a specific component when sur touch a received notification.
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md
http://docs.ionic.io/services/push/
In my app.component.ts constructor I try this :
platform.ready().then(() => {
//StatusBar.styleDefault();
Splashscreen.hide();
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
console.log(msg.app, "app");
console.log(msg.count, "count");
console.log(msg.image, "image");
console.log(msg.raw, "raw");
console.log(msg.sound, "sound");
console.log(msg.text, "text");
console.log(msg.title, "title");
});
});
It work well when my app isn't close or on pause. I can see my logs.
But when my app is closed or onpause, if I touch notification, my app open but I can't have my logs.
I tried this too :
this.push.on('notification', function(data) {
// do something with the push data
// then call finish to let the OS know we are done
this.push.finish(function() {
console.log("processing of push data is finished");
}, function() {
console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
}, data.additionalData.notId);
});
But I had this error :
Object [object Object] has no method 'on'
What I have to do ?
To have your notification event called when your application isn't in foreground, you have to add content-available: 1 into your push message.
Read this link

Cordova Android Push Notification With Action Button

I have used Push Plugin , when i am sending push with action button 1)accept 2)ignore.
when notification came , i was clicked on "accept" button . but i want parameters with the "accept" button callback. from that i will identify with notification's "accept" was called.
code reference
//initialization of push object
var push = PushNotification.init({
"android": {
"alert": "true",
"senderID": CONFIG.PROJECT_NUMBER,
"icon": "img/ionic.png",
"iconColor": "blue",
"badge": "true"
},
"ios": {
"alert": "true",
"badge": "true",
"sound": "true"
},
"windows": {
}
});
//listner for getting registration detail of device
push.on('registration', function(data) {
device_id_for_push=data.registrationId;
});
//listner called on new push notification
push.on('notification', function(data) {
// app.onPushAccept(data);
alert("on notification");
alert(JSON.stringify(data));
});
//error listner
push.on('error', function(e) {
// alert(e);
// alert("push error");
});
app.onPushAccept=function(data){
alert("onPushAccept")
alert(JSON.stringify(data));
// cordova.plugins.notification.badge.clear();
// cordova.plugins.notification.badge.increase();
}
in code "app.onPushAccept" function is callback of "accept" button..
Please help me as soon as possible.
Thank You..
Android Push Notification (Only)
Step 1 - First of all go to given below directory
plugins > phonegap-plugin-push > src > android > com > adobe > phonegap > push
Step 2 - Open GCMIntentService.java File from above directory
Step 3 - Determine function calling "createActions" and
Add actual parameter "requestCode" like...
createActions(extras,mBuilder,resources,packageName,notId,requestCode);
Step 4 - Determine function definition "createActions" and
Add formal parameter "int requestCode" like...
private void createActions(Bundle extras, NotificationCompat.Builder mBuilder, Resources resources, String packageName, int notId,int requestCode)
Step 5 - In function definition "createActions" and inside for loops
Change second parameter from "i" to "requestCode" like...
pIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pIntent = PendingIntent.getBroadcast(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Step 6 - After completing above all steps remove android platform if already added platform Then add android platform.
Sorry and improve if any mistake founds in my solution.
Okay, first imagine you are sending the following payload:
{
"registration_ids": ["my device id"],
"data": {
"title": "My title",
"message": "My message.",
"actions": [
{ "title": "Accept", "callback": "app.accept", "foreground": true},
{ "title": "Ignore", "callback": "app.ignore", "foreground": false}
]
}
}
and you have setup the following action button handlers:
app.accept = function(data} {
// do something
}
app.ignore = function(data} {
// do something
}
so now you have two options you can either put something in the push payload that uniquely identifies the push that was received which will be put in data.additionalData or modify the callbacks to call another event handler:
app.accept = function(data} {
app.processPush('accept', data);
}
app.ignore = function(data} {
app.processPush('ignore', data);
}
app.processPush = function(type, data) {
if (type === 'accept') {
// do accept stuff
} else if (type === 'ignore') {
// do ignore stuff
}
}
Use navigator.notification.confirm method of the plugin cordova-plugin-dialogs
it displays a customizable confirmation dialog box.
Syntax
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
message: Dialog message. (String)
confirmCallback: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). (Function)
title: Dialog title. (String) (Optional, defaults to Confirm)
buttonLabels: Array of strings specifying button labels. (Array) (Optional, defaults to [OK,Cancel])
you can change buttonLabels to ["Accept","Ignore"]
to satisfy your needs.
Example
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Accept','Ignore'] // buttonLabels
);

Ionic framework don't save token

I have a problem with Ionic framework. I follow the guide to receive and send push notification, but something doesn't work.
When I launch the app, I press button Identify, and show my an alert that say the user ID. After, I press on register button, the phone show me an alert that contains the Device token(ANDROID). But when I go to ionic.io, in the dashboard of my app, the device token there isn't.
If I don't have the token saved on my dashboard, I can't send push notification.
Anyone can help me?
This is my controller.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $rootScope, $ionicUser, $ionicPush) {
// Identifies a user with the Ionic User service
$scope.identifyUser = function() {
console.log('Ionic User: Identifying with Ionic User service');
var user = $ionicUser.get();
if(!user.user_id) {
// Set your user_id here, or generate a random one.
user.user_id = $ionicUser.generateGUID();
};
// Add some metadata to your user object.
angular.extend(user, {
name: 'Ionitron',
bio: 'I come from planet Ion'
});
// Identify your user with the Ionic User Service
$ionicUser.identify(user).then(function(){
$scope.identified = true;
alert('Identified user ' + user.name + '\n ID ' + user.user_id);
});
};
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
console.log('Got token', data.token, data.platform);
// Do something with the token
});
// Registers a device for push notifications and stores its token
$scope.pushRegister = function() {
console.log('Ionic Push: Registering user');
// Register with the Ionic Push service. All parameters are optional.
$ionicPush.register({
canShowAlert: true, //Can pushes show an alert on your screen?
canSetBadge: true, //Can pushes update app icon badges?
canPlaySound: true, //Can notifications play a sound?
canRunActionsOnWake: true, //Can run actions outside the app,
onNotification: function(notification) {
// Handle new push notifications here
// console.log(notification);
return true;
}
});
};
// Handles incoming device tokens
$rootScope.$on('$cordovaPush:tokenReceived', function(event, data) {
alert("Successfully registered token " + data.token);
console.log('Ionic Push: Got token ', data.token, data.platform);
$scope.token = data.token;
});
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
I follow the ionic guide step-by-step
In order to access the token on ionic.io , you have to push it through:
var push = new Ionic.Push();
var user = Ionic.User.current();
var callback = function(pushToken) {
console.log('Registered token:', pushToken.token);
user.addPushToken(pushToken);
user.save(); // you NEED to call a save after you add the token
}
push.register(callback);
as mentioned in the docs.

Categories

Resources