MAUI send sms without user interaction in Maui

Viewed 52

I want to send a SMS in MAUI without opening the default messages App, I want to send the SMS silently in background. Does anyone know how to implement it?

1 Answers

Here is the implementation in MAUI. Tested for Android and it works without opening the messages app. Here is the implementation for Android and iOS (not tested). in the shared project create this class:

 public partial class SmsService
{
   public partial void Send(string address, string message);
}

Implementation for Android platform:

public partial class SmsService
{
    public partial void Send(string phonenbr, string message)
    {
        SmsManager smsM = SmsManager.Default;
        smsM.SendTextMessage(phonenbr, null, message, null, null);
    }
}

Implementation for iOS platform (not tested):

public partial class SmsService
{
    public partial void Send(string address, string message)
    {
        if (!MFMailComposeViewController.CanSendMail)
            return;

        MFMessageComposeViewController smsController = new MFMessageComposeViewController();

        smsController.Recipients = new[] { address };
        smsController.Body = message;
        EventHandler<MFMessageComposeResultEventArgs> handler = null;
        handler = (sender, args) =>
        {
            smsController.Finished -= handler;
            var uiViewController = sender as UIViewController;
            if (uiViewController == null)
            {
                throw new ArgumentException("sender");
            }
            uiViewController.DismissViewControllerAsync(true);
        };
        smsController.Finished += handler;
 UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewControllerAsync(smsController, true);
    }
}
Related