In the last article, I showed you how to send SMS in android. In this article, we will see how to receive SMS messages. We can add the interested phone numbers in the settings.
We will start with the permissions required.
Receive SMS Permissions
We only need receive permission android.permission.RECEIVE_SMS
. In case you also want to read SMS messages from the Inbox then you need android.permission.READ_SMS
.
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
Intent Filter to receive SMS
We also need to tell Android that we want to handle incoming SMS messages. In order to do this, we will add a <receiver>
to register a broadcast receiver to the manifest XML. We will also add an <intent-filter>
to let Android know that we want to launch a specific class when an SMS comes in.
Add the below in AnrdoidManifest.xml:
<receiver android:name="com.javarticles.android.SMSReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
Broadcast Receiver
SMSReceiver
is a BroadcastReceiver
. When SMS is received, onReceive
will be called. Here we will look into the interested numbers based on a setting. If the message has originated from one of those numbers, we will launch a new Activity, and pass the phone number and the SMS message to the activity.
SMSReceiver:
package com.javarticles.android; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.SmsMessage; public class SMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String phoneNumbers = PreferenceManager.getDefaultSharedPreferences( context).getString("phone_entries", ""); StringTokenizer tokenizer = new StringTokenizer(phoneNumbers, ","); Set<String> phoneEnrties = new HashSet<String>(); while (tokenizer.hasMoreTokens()) { phoneEnrties.add(tokenizer.nextToken().trim()); } Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i]= SmsMessage.createFromPdu((byte[]) pdus[i]); String address = messages[i].getOriginatingAddress(); if (phoneEnrties.contains(address)) { Intent newintent = new Intent(context, MainActivity.class); newintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); newintent.putExtra("address", address); newintent.putExtra("message", messages[i].getDisplayMessageBody()); context.startActivity(newintent); } } } }
Main Activity
In the main activity, we will get the SMS data from the intent and set the text fields.
MainActivity:
package com.javarticles.android; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); Bundle extras = getIntent().getExtras(); if (extras != null) { String address = extras.getString("address"); String message = extras.getString("message"); TextView addressField = (TextView) findViewById(R.id.address); TextView messageField = (TextView) findViewById(R.id.message); addressField.setText(address); messageField.setText(message); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.settings: startActivity(new Intent(this, SettingsActivity.class)); } return super.onOptionsItemSelected(item); } }
Layout will have couple of text fields, one for phone number and the other for the message.
welcome.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.javarticles.android.DatePickerExample" > <TextView android:id="@+id/welcome" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="40dp" android:layout_marginTop="18dp" android:text="@string/welcome" android:textColor="@color/welcome_text_color" android:textSize="20sp" /> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Complete manifest XML
Let’s have a look at the android manifest XML.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javarticles.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:maxSdkVersion="22" android:minSdkVersion="14" android:targetSdkVersion="22" /> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher_sandbox" android:label="@string/app_name" > <activity android:name="com.javarticles.android.MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.javarticles.android.SMSReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> <activity android:name="com.javarticles.android.SettingsActivity" /> </application> </manifest>
Run the application
Main screen.
Set the interested phone numbers in the settings. If more than one, enter them comma separated.
Open ‘Emulator Control’ to send spoof SMS. To open the ‘Emulator Control’, Go to Windows->others->Android->’Emulator Control’.
Send SMS.
SMS shows up in the main page
Download source code
This was an example about Android SMS receive. You can download the source code here: receiveSMS.zip