addEventListener in ionic 3 - android

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

Related

How to read FCM playload inside mobile device?

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

React Native: Handle silent push notification

Im using react-native-firebase for handling push notification for our React Native app (for android and iOS).
I noticed that there is only have 1 callback for a push notification that is received when the app is running (foreground or background) and not when its closed or killed.
firebase
.notifications()
.onNotification(notification => {
console.log('Notification received');
);
But if the app is closed or killed, it will just put the notification in the tray and will not execute the console.log above.
Then enter silent push notification. So when I just send data part in the payload of the notification and even if app is in foreground, the callback above wont be triggered.
I don't see other callbacks that would help on receiving silent push notifications.
So how do we handle push notification in the javascript part?
You don't need additional packages like suggested in other answers.
Use RNFirebase.io, you can handle this easily.
If you receive Notification if App is in Background, you have to handle it by your own to display this Notification. As an example see my init-Method for Push-Notifications.
import firebase from 'react-native-firebase';
const notifications = firebase.notifications();
....
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
You do it with displayNotification. But make sure, that you set the Notification-Channel before calling it, because else it wouldn't work on >= Android 8.0
BTW: Make sure, that you fully setup Firebase and grant all needed Permissions to be able to listen for Notifications if App is closed or in Background. (https://rnfirebase.io/docs/v5.x.x/notifications/android)
Appendix
I add this as example to show how I implemented the firebase-notification-stuff as a tiny library (remove the redux-stuff if you don't need it):
import firebase from 'react-native-firebase';
import { saveNotificationToken } from 'app/actions/firebase';
import reduxStore from './reduxStore';
import NavigationService from './NavigationService';
const messaging = firebase.messaging();
const notifications = firebase.notifications();
const crashlytics = firebase.crashlytics();
function registerNotifChannels() {
try {
// Notification-Channels is a must-have for Android >= 8
const channel = new firebase.notifications.Android.Channel(
'app-infos',
'App Infos',
firebase.notifications.Android.Importance.Max,
).setDescription('General Information');
notifications.android.createChannel(channel);
} catch (error) {
crashlytics.log(`Error while creating notification-channel \n ${error}`);
}
}
// This is the Promise object that we use to initialise the push
// notifications. It will resolve when the token was successfully retrieved. The
// token is returned as the value of the Promise.
const initPushNotifs = new Promise(async (resolve, reject) => {
try {
const isPermitted = await messaging.hasPermission();
if (isPermitted) {
registerNotifChannels();
try {
const token = await messaging.getToken();
if (token) {
resolve(token);
}
} catch (error) {
crashlytics.log(`Error: failed to get notification-token \n ${error}`);
}
}
} catch (error) {
crashlytics.log(`Error while checking notification-permission\n ${error}`);
}
// If we get this far then there was no token available (or something went
// wrong trying to get it)
reject();
});
function init() {
// Initialise the push notifications, then save the token when/if it's available
initPushNotifs.then(token => reduxStore.dispatch(saveNotificationToken(token)));
// Save the (new) token whenever it changes
messaging.onTokenRefresh(token => reduxStore.dispatch(saveNotificationToken(token)));
notifications.onNotification((notif) => {
notif.android.setChannelId('app-infos');
notifications.displayNotification(notif);
});
notifications.onNotificationOpened((notif) => {
const { notification: { _data: { chatroom: chatRoomId } } = {} } = notif;
if (chatRoomId) {
NavigationService.navigate('ChatRoom', { chatRoomId });
}
});
}
export default {
init,
};
With this, only go to your index.js file (or your root-file for your app, how ever it will be named) and call the init-Metod:
...
import LPFirebase from 'lib/LPFirebase';
LPFirebase.init();

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.

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

onSMSArrive cordova sms plugins executed more than once

I was developing an app that have capability to read sms content when the user get sms.
So I use ionic and cordova sms plugin to read the sms content. But when user get a sms and triggered the onSMSArrive event provided by the plugin, it did work and can read the sms content.
The problem is it execute (read the sms) more then once, tree times to be exact.
I place this code as a service in ionic.
app.factory('$smsarrive', [function() {
return {
periksa:function() {
if (SMS) SMS.enableIntercept(true, function() {
console.log("some debug hint here");
}, function(){
console.log("some debug hint here");
});
if(SMS) SMS.startWatch(function() {
//update('watching', 'watching started');
console.log("some debug hint here");
}, function(){
//updateStatus('failed to start watching');
console.log("some debug hint here");
});
document.addEventListener('onSMSArrive', function(e) {
var sms = e.data;
var isiSms = sms.body;
if (isiSms.match(/FC0019229/g)!=null) {
if (isiSms.match(/Berhasil/g)!=null) {
console.log("Isi pulsa Berhasil");
} else if (isiSms.match(/Gagal/g)) {
console.log("Isi pulsa Gagal");
} else {
console.log(isiSms);
}
} else {
console.log("some hint here");
}
console.log("ASLI : "+isiSms);
});
}
}
}])
and execute that service whenever a controller of a view is
$scope.$on('$ionicView.enter', function() {
$smsarrive.periksa();
})
Any suggestion? And also sorry for bad english.
i use this plugin
From what I understand in your code examples, you are executing the function "periksa" every time a view is entered ( that's what fires the '$ionicView.enter' event). Then also, you are creating an EventListener for SMS messages every time you execute 'periksa' (every time a view is entered).
So, if you have entered three views, you would have three listeners firing for the arrival of an SMS onSMSArrive.
So, I think you should only Start Watching, and add the EventListener, once, when starting the app (in app.js, inside .run, when $ionicPlatform.ready()).
.run(function($ionicPlatform, $smsarrive) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
if(( /(ipad|iphone|ipod|android)/i.test(navigator.userAgent) )) {
if (! SMS ) { alert( 'SMS plugin not ready' ); return; }
SMS.startWatch(function(){
console.log('Watching');
}, function(){
console.log('Not Watching');
});
document.addEventListener('onSMSArrive', function(e){
var data = e.data;
$smsarrive.periksa(data);
});
} else {
alert('need run on mobile device for full functionalities.');
}
});
Then, your 'periksa' function should only receive the data as a parameter, for processing and disposing of the results.
Let me know if this was helpful, i'm also studying this framework and I have this plugin working in my App.

Categories

Resources