Hidden Android APIs: hiding SMS messages to the default SMS receiver

www.spiroprojects.com

In a previous tutorial we saw how to take advantage of the hidden Android APIs to listen to incoming SMS messages.
Now suppose that we want to listen to specific SMS messages (messages coming from a particular number or containing specific strings) and to hide them to the default SMS receiver (like Google Hangout or other client).







As in the previous tutorial we have to declare a BroadcastReceiver in the AndroidManifest.xml file. However, in order to take priority over the default SMS receiver, we also have to set a high priority for our SMS BroadcastReceiver:

<receiver android:name="com.androidthetechinalblog.SMSReceiver">
   <intent-filter android:priority="9999">
      <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
   </intent-filter>
</receiver>
  
Now we just have to make some minor changes to the SMSReceiver class: 

public class SMSReceiver extends BroadcastReceiver {
 
 public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
 
  if(action.equals(“android.provider.Telephony.SMS_RECEIVED”)) {
   Object incomingSMSs[] = (Object[]) intent.getSerializableExtra(“pdus”);
    
   for(Object tmp : incomingSMSs) {
    byte message[] = (byte[]) tmp;
    SmsMessage smsMessage = SmsMessage.createFromPdu(message);

    String phoneNumber = smsMessage.getOriginatingAddress();
    String messageBody = smsMessage.getMessageBody();

    if(phoneNumber.equals("3457148596") || messageBody.contains("test")) {
       //we have found our SMS! here you can perform some actions
       abortBroadcast();
       setResultData(null);
    }
   }
  }
 }
}

As you can see, by calling abortBroadcast() and setResultData(null) (methods working only for "ordered broadcasts", like in our example) we make sure that our SMS won't be propagated to any other receiver.
 
Previous
Next Post »