Read And List SMS With Ionic 2 Apps For Android

Share on FacebookTweet about this on TwitterShare on Google+Share on RedditShare on StumbleUponDigg thisFlattr the authorPin on PinterestShare on TumblrShare on LinkedInPrint this pageBuffer this page

There may come a time when you need to read the SMSes that the user has in the inbox with your app created using Ionic 2. In this tutorial we will see exactly how achieve that.

In this tutorial, we will use the cordova-plugin-sms. A thing to note here right off the bat is that the plugin offers the ability to list only the latest 10 SMSes in the free version. For more you need to buy the license key which you can do so via the link in the documentation. Also, note that this plugin works for only Android apps.

This plugin not only offers the ability to list messages but also can send messages. You can send SMSes without any restriction in the free version except the list feature as mentioned above.

Let’s code a sample app.

Step 1 )

We will create a fresh Ionic 2 project. I will use the blank template you can use another template that you want.

After having navigated inside the smsList directory we will add the Android platform.

Step 2 )

Now it’s time to add the cordova-plugin-sms plugin to our application we do that by running the following command

Note: If you are building for API level 23 and above, you will need to add the cordova-plugin-android-permissions plugin for Android. Basically, you will need to ask the user for the permission to read SMSes. Check out the documentation of the plugin for more.

 

 

Step 3)

Open the project folder in you favorite editor and open the file in src\pages\home\home.html

Inside home.html we will put the following code

As you can see we are creating a button on line 10 which will call a function getSMS(). We also have *ngFor on line 12 that will loop over every object in the smses array.

Als0 note that I am using ion-icon with *ngIf that will show or hide the star icon depending on the value sms.read==0 is true or not. What this will do is it will show a star alongside all the messages that have not been read.

Step 4)

After creating our view and we created a button in it, it’s now time to add functionality to our app we do that by opening up src\pages\home\home.ts file and adding the following code.

As shown we are checking for the availability of the SMS object on line 16. Then we are using the SMS.list() method to list all the messages. A thing to note that we have used the setTimeout() function here. This is because I found that the data was not binding to the view and it needed two taps on the button to display the list. If you find that it works without setTimeout() you can remove it.

 

Let’s break the SMS.list() method down and understand it better. It takes three arguments the first is a filter object { } (More on the filter object later). The second and third are success and error callback functions.

The data we get back is an array of objects and each object has the following structure

Where the address it the number from where the SMS came from, the body is the actual text of the SMS and so on.

 

SMS Filter Values

So what is this filter object {} that we passed as the first argument in the SMS.list() method.Well as the name suggests it provides a way to filter the SMS data that we get back. This can be really handy as you can get specific SMSes based on the SMS text string, you can get all unread SMSes, you can also get SMSes from a particular sender, etc. Let’s see a quick example of how you can do this

 

 

The above code is taken from the docs here and is pretty well commented out and is pretty self-explanatory.

Note:

This plugin will not work in the browser. You will need to install the app on a device and run the app for this to work.

Known Issues:

The plugin automatically adds few permistions to the AndoridManifest.xml file during the build process. But there are times that you may get an Permisson Denial error which looks somewhat like the following

Permission Denial: reading com.android.providers.telephony.SmsProvider uri content ….
requires android.permission.READ_SMS, or grantUriPermission()

To solve this open up platforms\android\AndroidManifest.xml file and add the following to inside the <widget> tag

 

Conclusion

The cordova-plugin-sms is a good SMS plugin if you want to have the ability to Read as well as Send SMSes. The negative thing about the plugin is that it is an Android only plugin. For most cases the free version of the plugin will do. However, if you have an app that needs to list more that 10 SMSes you should definitely consider buying the License key.

 

Download Code:


Code Will Be Sent Via Email

 

Leave Me Your Questions And Feedback

Getting your feedback inspires me the most so hit me up in the comments here or on the comments section on my YouTube Channel or on twitter @pointDeveloper

Consider Subscribing / Donating
Subscribe To Mailing List
Donate
If my site was helpful to you, then please consider donating via paypal:

Prantik Vaghela (pointdeveloper)

Hi my name is Prantik Vaghela. I have done my Bachelors and Masters in Computer Science and am a web developer and now a Tutor through my blog. :-)

  • Pingback: Ionic 2 Beginner : Send SMS With Ionic 2 And Cordova SMS Plugin - pointDeveloper.com()

  • Pingback: How To Send SMS With Ionic Framework And ngCordova - pointDeveloper.com()

  • Pingback: Sending SMS With Ionic 2 App For Android - pointDeveloper.com()

  • Amadu Abdul

    Great Article Prantik. Your post is the most elaborate tutorial i could find on how to read SMSes with ionic. The issue I have is that i started with Angularjs and used ngcordova for sending SMSses but when i followed your tutorial, i kept getting errors. Particularly ReferenceError: SMS is not defined . I’m quite sure its because your method wasn’t for AngularJs so I was wondering if there was a way i could still use your method while sticking with AngularJs

    • the ‘ReferenceError: SMS is not defined’ comes when you are calling the plugin before the sms api is available or you are using in a browser.. the plugin works fine with angular.. i suggest you run in on a device or make sure that you are calling the sms object after the deviceready() event.

      -Regards

      • Amadu Abdul

        Thanks for the reply. I ended up having to recreate the project with ionic 2, copy all relevant code to it and follow the steps in your reply before it worked.
        Thanks for the help 🙂

  • Martin Oberndorfer

    Hey pointdeveloper!
    I’m new to the topic and tried to follow your instructions. Everything seems fine, but the import for the SMS object is missing.
    i.e. import {SMS} from ‘ionic-native’;
    but then i can only send sms. i have the correct cordova-plugin-sms installed but i can’t get it running…
    Please help, thank you in advance!

    • there are two plugins out there..cordova-plugin-sms and cordova-sms-plugin..The ionic-native has the cordova-sms-plugin, which can only send SMSes..The other plugin can do more list as well. The name confusion got me to at first.

      import {SMS} from ‘ionic-native’; is not in this post because when i wrote it ionic was still using JavaScript now it has moved to TypeScript. I will update this post as soon as ionic gets it’s first release.

      Both plugins are listed below
      https://github.com/floatinghotpot/cordova-plugin-sms
      https://github.com/cordova-sms/cordova-sms-plugin

      -Thanks

  • Behi Seven

    HI, I use this but error
    E/DatabaseUtils(2852): java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider uri content://sms/inbox from pid=6734, uid=10076 requires android.permission.READ_SMS, or grantUriPermission()

    • The permissions will be added automatically when you add the plugin so try to remove the plugin and add it again with
      ionic pluign add cordova-plugin-sms

      If that doesn’t work you need to add the following inside the platform/android/androidmanifest.xml file

  • sketchthat

    I can’t get this working on Android (7.0) Nougat.

    I get the following error;

    Permission Denial: reading com.android.providers.telephony.SmsProvider uri content ….
    requires android.permission.READ_SMS, or grantUriPermission()

    I understand I need to request the permission during Run Time with the latest Android version but I don’t understand how to do this with Ionic2.

    • The plugin adds the permissions for you in the platforms/android/AndroidManifest.xml ..On my device which is android 5 it has the following

      You can try adding them manually and see if that works.

      I have not checked it for higher versions for android..I took a look at the github repo of the plugin for you and found this
      https://github.com/floatinghotpot/cordova-plugin-sms/issues/34

      Hope it helps 🙂

      • sketchthat

        Thanks a lot, that solved it!

        • @sketchthat:disqus i am also facing the same issue how did you solve i to tried that stack question but no positive output still getting same permission denial.

          • sketchthat

            In your home.ts file you need to add the following import and update the constructor.

            import { NavController, Platform, Nav } from ‘ionic-angular’;

            constructor(public navCtrl: NavController, public platform: Platform) {
            platform.ready().then(() => {
            var permissions = cordova.plugins.permissions;

            permissions.hasPermission(permissions.READ_SMS, checkPermissionCallback, null);

            this.getSMS();

            function checkPermissionCallback(status) {
            if(!status.hasPermission) {
            var errorCallback = function() {
            alert(‘READ_SMS permission is not turned on’);
            }

            permissions.requestPermission(
            permissions.READ_SMS,
            function(status) {
            if(!status.hasPermission) {
            errorCallback();
            }
            },
            errorCallback);
            }
            }
            });

          • Sebastian Hernandez

            Thank you! This aproach worked for me at 24 SDK Version, but i had to install android permissions plugin:
            cordova plugin add cordova-plugin-android-permissions

          • Thanks..I did not check it at API 24..will update the post to mention this.

          • ganapathiraju abhisekhervarma

            Dear sir i used like this what you had said like this iam facing “cordova” is an error can u sugest me any thing

            import { NavController, Platform, Nav } from ‘ionic-angular’;

            constructor(public navCtrl: NavController, public platform: Platform) {
            platform.ready().then(() => {
            var permissions = cordova.plugins.permissions;

            permissions.hasPermission(permissions.READ_SMS, checkPermissionCallback, null);

            this.getSMS();

            function checkPermissionCallback(status) {
            if(!status.hasPermission) {
            var errorCallback = function() {
            alert(‘READ_SMS permission is not turned on’);
            }

            permissions.requestPermission(
            permissions.READ_SMS,
            function(status) {
            if(!status.hasPermission) {
            errorCallback();
            }
            },
            errorCallback);
            }
            }
            });

          • ganapathiraju abhisekhervarma

            please reply fast iam waiting

          • Can you tell me what is the error message that you are getting?

  • I am facing this error: Permission Denial: reading com.android.providers.telephony.SmsProvider uri content://sms/inbox from pid=15835, uid=10100 requires android.permission.READ_SMS, or grantUriPermission()

    I tried all the way that you have mentioned but still facing the permission denail problem

    • have you tries adding the following to config.xml

      • This peace of code is already available in my config.xml. if any information you need from my side please let me know.

        • have you tried adding all the permissions as followins

  • darshan marode

    I am getting error “Cannot find name ‘cordova'”

  • Anup

    I am not getting complete list of message present in my inbox, and i am not getting the clue, whether the message is send or receive. Please guide me.

    • As I have written in the Conclusion section of the post, the plugin will only get 10 SMSes. For more, you will have to buy the a licence for it.

      Thanks,
      -Prantik