Receiving SMS messages

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.

How to do it...

To listen for incoming SMS messages, we will use a broadcast receiver:

  1. First, we will need a permission to receive SMS messages:
    [assembly: UsesPermission(Manifest.Permission.ReceiveSms)]
  2. Next, we will need a broadcast receiver that listens for incoming messages:
    [BroadcastReceiver]
    [IntentFilter(
      new[] { "android.provider.Telephony.SMS_RECEIVED" })]
    public class SmsReceiver : BroadcastReceiver {
      public override void OnReceive(
      Context context, Intent intent) {
      }
    }
  3. Finally, we process the incoming intent and read the SMS message:
    if (intent.HasExtra("pdus")) ...

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.