We may be creating an app that requires the user to send an SMS message to a specific number.
To send an SMS message, we make use of the SmsManager
instance:
SmsManager
instance, we require a permission:[assembly: UsesPermission(Manifest.Permission.SendSms)]
SendTextMessage
:var number = "0123456789"; var message = "SMS Message Text..."; var manager = SmsManager.Default; manager.SendTextMessage(number, null, message, null, null);
If we need to verify that the message was sent successfully, we can use intents that will be broadcast with the operation status:
var sentIntent = PendingIntent.GetBroadcast( this, 0, new Intent("xamarincookbook.Send"), 0); var deliveredIntent = PendingIntent.GetBroadcast( this, 0, new Intent("xamarincookbook.Delivered"), 0); manager.SendTextMessage( number, null, message, sentIntent, deliveredIntent);
public class SmsSentReceiver : BroadcastReceiver { public override void OnReceive( Context context, Intent intent) { if (intent.Action == "xamarincookbook.Send") { var sendSuccess = ResultCode == Result.Ok; } if (intent.Action == "xamarincookbook.Delivered") { var deliverySuccess = ResultCode == Result.Ok; } } }
receiver = new SmsSentReceiver(); RegisterReceiver( receiver, new IntentFilter("xamarincookbook.Send")); RegisterReceiver( receiver, new IntentFilter("xamarincookbook.Delivered"));
UnregisterReceiver(receiver);
Sending SMS messages can be done from within an Android app without user intervention.
To send SMS messages, we first need to request the SendSms
permission. This is required because sending an SMS message involves a cost for the user.
Once we have the permission, we can then obtain an instance of the SmsManager
instance. We then pass the destination number and message to the SendTextMessage()
method.
The second last parameter of the SendTextMessage()
method is a PendingIntent
instance that will be broadcast if the message is successfully sent out or if there is an error in sending. The ResultCode
will either be Ok
if it is successful, or another value if there is an error.
To confirm that the SMS is delivered to the recipient, we provide a PendingIntent
instance to the last parameter. This intent will be broadcast when the message has been delivered.
If the message is going to be too long for a single message, we can use the DivideMessage()
method on the SmsManager
instance to break the message up into fragments.
The fragments are then sent to a recipient using the SendMultipartTextMessage()
method. We pass the collection of fragments along with a collection of pending intents that should be broadcast as each fragment is sent and delivered.