Our app may be using SMS messages to verify the phone number that the user has specified. If we want to do this, we may want to listen for an incoming SMS message.
To listen for incoming SMS messages, we will use a broadcast receiver:
[assembly: UsesPermission(Manifest.Permission.ReceiveSms)]
[BroadcastReceiver] [IntentFilter( new[] { "android.provider.Telephony.SMS_RECEIVED" })] public class SmsReceiver : BroadcastReceiver { public override void OnReceive( Context context, Intent intent) { } }
if (intent.HasExtra("pdus")) { var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus"); string address = ""; string message = ""; foreach (var item in smsArray) { var sms = SmsMessage.CreateFromPdu((byte[])item); message += sms.MessageBody; address = sms.OriginatingAddress; } }
Listening for incoming SMS messages is useful, especially as we can use them to verify the existence of a device. We can have an app requires that the user to have a valid mobile number. It can request that a server sends an SMS to the device, and when the message is received, allow the user to log in.
Before we can listen for incoming SMS messages, we require the ReceiveSms
permission.
We can receive events for incoming SMS messages if we register a broadcast receiver for the android.provider.Telephony.SMS_RECEIVED
intent action.
When the device receives an SMS message, we can read the message out of the pdus
extra. The extra contains an array of one or more message parts. Each part is an array of bytes that can be used to create a SmsMessage
object instance.
Once we have created a SmsMessage
instance using the static CreateFromPdu()
method, we can then read various properties to obtain information on each part.
As the message may be broken up into parts, we have to concatenate the message text obtained from the MessageBody
property. We can use the OriginatingAddress
property to obtain the number that the message was sent from.
If, for some reason, we do not wish to display the SMS notification on the device, we can stop the broadcast from being propagated to the default SMS app.
To do this, we use the InvokeAbortBroadcast()
method on the receiver. This will prevent the message from reaching the default SMS app, therefore, we need to be very careful when doing this.
We may have to ensure that our app receives the SMS before the default app, otherwise the abort operation will do nothing. To ensure this, we set the Priority
property in the [IntentFilter]
attribute as IntentFilterPriority.HighPriority
.