Simple SMS Reader app in Android using BroadcastReceiver class

Before I began coding Android apps, I was amazed how verification processes go like this: The Android app tells you they’ll send you an SMS containing verification code, and that you need to enter such code into a text field on the Android app. But when you receive the SMS, the verification code appears on the text field before you even type! I was like, whoa, how do they do that?

Now that I am able to develop simple Android apps, I already have an idea how it’s done.

We extend a class called BroadcastReceiver and implement its onReceive() method. This receiver is then registered either in the AndroidManifest.xml file, or registered as needed in a .java file (e.g., Activity)

I’m registering mine in my MainActivity file. I’ll provide the link to my project files on Github later on this page, but for now here’s what it looks like:

I first created a class called SmsReceiver which extends the BroadcastReceiver class that I mentioned earlier. Inside it, there’s an implemented method onReceive(), where we first check if the Intent’s action is android.provider.Telephony.SMS_RECEIVED, otherwise we do nothing. We read message(s) that the Android devices just received and get the originating address (e.g. phone number of sender) and message body. Then lastly, the TextViews in the XML file are updated with the originating address and message body so you could see that thea app works.

By the way, I used a Handler in this app so that I could set the values of TextViews inside the MainActivity’s XML file. A new Handler object is passed from MainActivity.onCreate() to the SmsReceiver constructor. And later on once the message originating address and message body are available in BroadcastReceiver.onReceive(), we use the handler to “post” and set the TextView values.

Now, for the source files of this Android app…

Feel free to download my Android project files here: Android-Incoming-SMS-Reader

Resource:
http://stackoverflow.com/a/14648933

Related Posts:

Posts that may be related to "Simple SMS Reader app in Android using BroadcastReceiver class":

Catzie

An odd human being who happens to have a variety of ever-changing interests, but right now they are programming, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert/drink flavors, obsessing about finding out how some things works, automation, anime, video games... Ran online dessert shops Cookies PH and Catzie's Cakery in her past life.

Leave a Reply

Your email address will not be published. Required fields are marked *