Android Filtering the text messages from a particular sender

Android Filtering the text messages from a particular sender


At first you have to create following class which extend the Broadcast receiver.

1: import android.content.BroadcastReceiver; 
2: import android.content.Context;
3: import android.content.Intent;
4: import android.content.SharedPreferences;
5: import android.os.Bundle;
6: import android.telephony.SmsMessage;
7: import android.util.Log;
8: import android.widget.Toast;
9: public class Filter extends BroadcastReceiver {
10: @Override
11: public void onReceive(Context context, Intent intent) {
12: if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
13: Bundle extras = intent.getExtras();
14: if (extras != null) {
15: Object[] pdus = (Object[])extras.get("pdus");
16: if (pdus.length < 1) return;
17: StringBuilder sb = new StringBuilder();
18: String sender = null;
19: for (int i = 0; i < pdus.length; i++) {
20: SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
21: if (sender == null){
22: sender = message.getOriginatingAddress(); //get the sender
23: }
24: String text = message.getMessageBody(); //get the message body
25: if (text != null){
26: sb.append(text);
27: }
28: }
29: String number = "+94717516043"; //add the number that you want to filter
30: if (sender.equals(number)) {
31: abortBroadcast(); // this will stop the filtered message going to the inbox.
32: }
33: }
34: }
35: }
36: }

You have to input sender you want to filter the text messages as the number and it is a string.
 Then you have to do couple changes to the manifest file.

First you have to add permission to the manifest file.

1: <uses-permission android_name="android.permission.RECEIVE_SMS"/> 
2: <uses-permission android_name="android.permission.READ_SMS"/>

Then you have to the following receiver tag to the manifest file. You have to it in the application tag.

1: <receiver android_name="com.example.smsfilter.Filter" > 
2: <intent-filter android_priority="1">
3: <action android_name="android.provider.Telephony.SMS_RECEIVED" />
4: </intent-filter>
5: </receiver>

Thats all you need to do. By looking at the logcat you can identify filtered messages sender and message body as follows.


download
alternative link download