Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to analyze incoming SMS on Android?

Tags:

android

sms

How can I code in Android such that my app can analyze an incoming SMS and perhaps block it or do something(maybe move to a different SMS folder) BEFORE the SMS actually raises a notification telling the user of a new SMS? I would target Android 2.1 and above.

I would want to analyse incoming SMS for user specified spam words, and if found would want to delete/mark as read/move the message to a different folder.

like image 416
Saurabh Kumar Avatar asked Jan 09 '11 05:01

Saurabh Kumar


People also ask

How do I read incoming messages?

In the “Notification Access” menu that appears, tap the toggle next to “Google.” Tap “Allow” in the window that appears to grant Google access. Head back to Google Assistant or say, “OK/Hey, Google,” again, and then repeat the, “Read my text messages,” instruction.


1 Answers

I use this code, as a BroadcastReceiver:

public void onReceive(Context context, Intent intent) 
{   
    //this stops notifications to others
    this.abortBroadcast();

    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();   
    SmsMessage[] msgs = null;
    String str = "";            
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            str += "SMS from " + msgs[i].getOriginatingAddress();
            from = msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            msg = msgs[i].getMessageBody().toString();
            str += "\n"; 
        }
        if(checksomething){
            //make your actions
            //and no alert notification and sms not in inbox
        }
        else{
            //continue the normal process of sms and will get alert and reaches inbox
            this.clearAbortBroadcast();
        }
  }

remember to add it in manifest and add a higgest priority (100) for broadcast or sms will go first to inbox and get the alert notification.

    <receiver android:name=".SmsReceiver">
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
        </intent-filter>
    </receiver>

Hope it helps you.

like image 105
maztch Avatar answered Oct 10 '22 03:10

maztch