Android - How to intercept SMS messages and prevent them from appearing in the Inbox

Posted by Anuraj on Tuesday, March 31, 2015 Reading time :1 minute

.Net Android Visual Studio

Android allows app developers to intercept SMS, here is the code snippet, which will help you to get the sms details and if you require you can stop them appearing in the inbox.

First you need to set the permission for the app to receive and process SMS. You can do this by modifing the AndroidManifest.xml file.

AndroidManifest.xml file

Source :

<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

Now you need to write a BroadcastReceiver, which helps to process the SMS message.

[BroadcastReceiver (Enabled = true, Label = "SMS Receiver")]
public class SMSBroadcastReceiver : BroadcastReceiver
	public static readonly string IntentAction = "android.provider.Telephony.SMS_RECEIVED";

	public override void OnReceive (Context context, Intent intent)
		try {
			if (intent.Action != IntentAction) {

			var bundle = intent.Extras;

			if (bundle != null) {
				var pdus = (Java.Lang.Object[])bundle.Get ("pdus");
				var messages = new SmsMessage[pdus.Length];
				var stringBuilder = new StringBuilder ();
				for (int i = 0; i < messages.Length; i++) {
					messages [i] = SmsMessage.CreateFromPdu ((byte[])pdus [i]);
					stringBuilder.AppendFormat ("Message from  {0} here is the Content : {1}", 
						messages [i].OriginatingAddress.ToString (), messages [i].MessageBody.ToString ());
				Toast.MakeText (context, stringBuilder.ToString (), ToastLength.Long).Show ();
				//Uncomment next line if you want to skip the inbox.
				//InvokeAbortBroadcast ();
		} catch (Exception ex) {
			Toast.MakeText (context, ex.Message, ToastLength.Long).Show ();

And finally you need to register the BroadcastReceiver, you can do this like

RegisterReceiver (new SMSBroadcastReceiver(), new IntentFilter ("android.provider.Telephony.SMS_RECEIVED"));

You can use this technique to avoid SPAM messages by looking into the number or message content.

Note: You can verify this implementation using android emulator. You can find more details here - SMS Emulation

Happy Programming. :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub