Friday, May 13, 2011

Android Tip - How to intercept SMS messages and prevent them from appearing in the Messaging App?

Sometime back, I wrote an article on how to intercept incoming SMS messages in your Android application - http://mobiforge.com/developing/story/sms-messaging-android.

Ever since, I have received numerous questions on how you can prevent the incoming messages (that you are trying to intercept) from appearing in the Messaging application (and hence in the status bar). The solution to this is pretty straight-forward once you understand the concept of broadcast receivers.

Basically, your program registers a class SMSReceiver as a broadcast receiver to intercept incoming SMS messages:
       <receiver android:name=".SMSReceiver">
         <intent-filter>
             <action android:name="android.provider.Telephony.SMS_RECEIVED" />                  
         </intent-filter>
     </receiver>

When a SMS message is received, all applications (including the Messaging application) will take turn to handle the incoming message. So, in order to prevent the incoming message from being handled by the Messaging application, your application just needs to handle the message before the Messaging app has the chance to do so. To do this, add the android:priority attribute to the <intent-filter> element, like this:
        <receiver android:name=".SMSReceiver">
         <intent-filter android:priority="100">
             <action android:name="android.provider.Telephony.SMS_RECEIVED" />                  
         </intent-filter>
     </receiver>
Set this to a high number, such as 100. The higher the number, the earlier Android executes your application. So in this case, when an incoming message is received, your application will execute first, and you can decide what to do with the message. To prevent other applications from seeing the message, simply call the abortBroadcast() method in your broadcast receiver class (SMSReceiver):
        this.abortBroadcast();
Once you do this, no other applications will see your SMS message. :-) Have fun!

2 comments:

Unknown said...

Good post Sir. Regards
Abhilash Vijayakumar

Unknown said...

Thank You so much for help me out!!!!