This article is for Ionic V1 for current version of ionic Please Read this article working on Android visit Ionic 3 Cordova Read SMS plugin .
In Ionic Framework to read SMS messages from device you can use cordova plugin.
So, first of all install cordova SMS plugin in your application.
cordova plugin add cordova-plugin-sms
You can use these following methods.
sendSMS(address(s), text, successCallback, failureCallback);
listSMS(filter, successCallback, failureCallback);
deleteSMS(filter, successCallback, failureCallback);
startWatch(successCallback, failureCallback);
stopWatch(successCallback, failureCallback);
enableIntercept(on_off, successCallback, failureCallback);
restoreSMS(msg_or_msgs, successCallback, failureCallback);
setOptions(options, successCallback, failureCallback);
To Read List of SMS:-
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
var filter = {
box : 'inbox', // 'inbox' (default), 'sent', 'draft'
indexFrom : 0, // start from index 0
maxCount : 10, // count of SMS to return each time
};
if(SMS) SMS.listSMS(filter, function(data){
console.log(data);
},
function(err){
console.log('error list sms: ' + err);
});
});
})
Make sure always use method in Ionic Framework inside the $ionicPlatform.ready(function() {}; else it will not work.
To Read SMS on Arrive:-
First startWatch() watching for new messages the and when new message arrive onSMSArrive event is triggered. To read OTP SMS you can use this feature.
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(SMS) SMS.startWatch(function(){
console.log('watching started');
}, function(){
console.log('failed to start watching');
});
document.addEventListener('onSMSArrive', function(e){
var sms = e.data;
console.log(sms);
});
});
})
To Send SMS-
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(SMS) SMS.sendSMS("+9112345","msg",function(){
console.log("Sent");
}, function(e){
console.log("Error occurs")
});
});
})