Jaa


Xamarin.Essentials: SMS

The Sms class enables an application to open the default SMS application with a specified message to send to a recipient.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

To access the Sms functionality the following platform specific setup is required.

If your project's Target Android version is set to Android 11 (R API 30) you must update your Android Manifest with queries that are used with the new package visibility requirements.

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node:

<queries>
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="smsto"/>
  </intent>
</queries>

Using Sms

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

The SMS functionality works by calling the ComposeAsync method an SmsMessage that contains the message's recipient and the body of the message, both of which are optional.

public class SmsTest
{
    public async Task SendSms(string messageText, string recipient)
    {
        try
        {
            var message = new SmsMessage(messageText, new []{ recipient });
            await Sms.ComposeAsync(message);
        }
        catch (FeatureNotSupportedException ex)
        {
            // Sms is not supported on this device.
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}

Additionally, you can pass in multiple receipients to a SmsMessage:

public class SmsTest
{
    public async Task SendSms(string messageText, string[] recipients)
    {
        try
        {
            var message = new SmsMessage(messageText, recipients);
            await Sms.ComposeAsync(message);
        }
        catch (FeatureNotSupportedException ex)
        {
            // Sms is not supported on this device.
        }
        catch (Exception ex)
        {
            // Other error has occurred.
        }
    }
}

API

Find more Xamarin videos on Channel 9 and YouTube.