locked
How can I send a message (sms) automatically in android? RRS feed

  • Question

  • User388951 posted

    I want to send a message without opening the messaging application. Can I do it that?

    Wednesday, October 30, 2019 2:02 AM

Answers

  • User380718 posted

    @SpontonLuciano 1.you could define a interface in your form project

    public interface ISendMessage
     {
        void SendMessage(string phoneNumber,string content);
     }
    

    2. in your MainActivity.cs in Android.Project,let the MainActivity implements the interface ISendMessage:

       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity,ISendMessage
        {
    
            public void SendMessage(string phoneNumber,string content)
            {
                 if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms) == Permission.Granted)
                   {
                     SmsManager smsManager = SmsManager.Default;
                     // Split text message content (SMS length limit)
                     IList<string> divideContents = smsManager.DivideMessage(content);
    
                    foreach (string text in divideContents)
                      {
                       smsManager.SendTextMessage(phoneNumber, null, text, null, null);
                     }
                 }
               else
                {
                    ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.SendSms }, 1);
                }
            }
       }
    

    3. call in your page like :

     private async void BtnSendSMS_Clicked(object sender, EventArgs e)
      {
         DependencyService.Get<ISendMessage>().SendMessage(phonenumber,content);
      }
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, November 1, 2019 6:28 AM

All replies

  • User380718 posted

    There are two ways to send messages. 1.Call system SMS interface to send SMS directly; The main code is as follows (remember request runtime permission):

     public void sendSMS(String phoneNumber, String message)
          {
             // Get the SMS manager
             SmsManager smsManager = SmsManager.Default;
             // Split text message content (SMS length limit)
             IList<string> divideContents = smsManager.DivideMessage(message);
    
             foreach (string text in divideContents)
                {
                   smsManager.SendTextMessage(phoneNumber, null, text, null, null);
                }
    
           }
    

    add permission <uses-permission android:name="android.permission.SEND_SMS" /> 2. use the system send SMS function; The main code is as follows:

        Intent intent = new Intent(Intent.ActionSend, Android.Net.Uri.Parse("smsto:" + phoneNumber));
        intent.PutExtra("sms_body", message);
        StartActivity(intent);
    
    Wednesday, October 30, 2019 3:12 AM
  • User388951 posted

    @LeoZhu

    <ContentPage.Content>
        <StackLayout x:Name="SMSSender" Orientation="Horizontal">
            <Image Source="Messages" />
            <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
                <Label Text="Write phone number:" />
                <Entry  x:Name="SMSPhoneNumber" Placeholder="(333) 333-3333" />
                <Label  Text ="Write your body message here"/>
                <Entry  x:Name="SMSBody" Placeholder="This is a message for your :3!!!" HeightRequest="120"/>
                <Button x:Name="BtnSendSMS" Text="Send message" Clicked="BtnSendSMS_Clicked" BackgroundColor="#71d349" TextColor="White" BorderRadius="10"/>
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
    

    using Android.Content; using Android.Telephony; using Plugin.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml;

    namespace SMSDemo.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Page1 : ContentPage { public Page1() { InitializeComponent(); }

        private async void BtnSendSMS_Clicked(object sender, EventArgs e)
        {
            sendSMS("qqqq", "7777888888");
    
        }
    
    
        public void sendSMS(String phoneNumber, String message)
        {
            // Get the SMS manager
            SmsManager smsManager = SmsManager.Default;
            // Split text message content (SMS length limit)
            IList<string> divideContents = smsManager.DivideMessage(message);
    
            foreach (string text in divideContents)
            {
                smsManager.SendTextMessage(phoneNumber, null, text, null, null);
            }
    
        }
    }
    

    }

    This is My androidManifiest

    and i get this exception

    Thursday, October 31, 2019 9:52 AM
  • User76049 posted

    If the permission is a protected permission (which this probably is for good reason) you will have to ask the user's permission before you can send an SMS. Doesn't matter if you specify it in the manifest for certain permissions, you will have to ask. This also depends on the Android API level.

    Thursday, October 31, 2019 12:05 PM
  • User76049 posted

    https://developer.android.com/training/permissions/requesting

    https://stackoverflow.com/questions/36936914/list-of-android-permissions-normal-permissions-and-dangerous-permissions-in-api

    Dangerous

    READ_CALENDAR WRITE_CALENDAR CAMERA READ_CONTACTS WRITE_CONTACTS GET_ACCOUNTS ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION RECORD_AUDIO READ_PHONE_STATE READ_PHONE_NUMBERS CALL_PHONE ANSWER_PHONE_CALLS READ_CALL_LOG WRITE_CALL_LOG ADD_VOICEMAIL USE_SIP PROCESS_OUTGOING_CALLS BODY_SENSORS SEND_SMS << RECEIVE_SMS READ_SMS RECEIVE_WAP_PUSH RECEIVE_MMS READ_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE

    Thursday, October 31, 2019 12:07 PM
  • User380718 posted

    @SpontonLuciano the codes i give you is in Xamarin.Android,if you want to use it in Xamarin.Forms ,you could use DependencyService to call it

    after android 6.0,you should request runtime permission.you could do like :

          if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms) == Permission.Granted)
                {
    
    
                    SmsManager smsManager = SmsManager.Default;
                    // Split text message content (SMS length limit)
                    IList<string> divideContents = smsManager.DivideMessage(message);
    
                    foreach (string text in divideContents)
                    {
                        smsManager.SendTextMessage(phonenumber, null, text, null, null);
                    }
                }
            else
            {
    
                    ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.SendSms }, 1);
             }
    
    Friday, November 1, 2019 3:56 AM
  • User388951 posted

    @LeoZhu That works if I put it on MainActivity.cs in the SMSDemo.Droid proyect but I need to put it on a xaml page (Page1) of my SMSDemo portable proyect and I get this error when try to put it there

    cant't convert SMSDemo.Views.Page1 to Android.Content.Context

    How can I solve it?

    Friday, November 1, 2019 6:11 AM
  • User380718 posted

    @SpontonLuciano 1.you could define a interface in your form project

    public interface ISendMessage
     {
        void SendMessage(string phoneNumber,string content);
     }
    

    2. in your MainActivity.cs in Android.Project,let the MainActivity implements the interface ISendMessage:

       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity,ISendMessage
        {
    
            public void SendMessage(string phoneNumber,string content)
            {
                 if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms) == Permission.Granted)
                   {
                     SmsManager smsManager = SmsManager.Default;
                     // Split text message content (SMS length limit)
                     IList<string> divideContents = smsManager.DivideMessage(content);
    
                    foreach (string text in divideContents)
                      {
                       smsManager.SendTextMessage(phoneNumber, null, text, null, null);
                     }
                 }
               else
                {
                    ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.SendSms }, 1);
                }
            }
       }
    

    3. call in your page like :

     private async void BtnSendSMS_Clicked(object sender, EventArgs e)
      {
         DependencyService.Get<ISendMessage>().SendMessage(phonenumber,content);
      }
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Friday, November 1, 2019 6:28 AM
  • User388951 posted

    @LeoZhu

    //////// My MainActivity in Droid proyect

    using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Support.V4.Content; using Android; using Android.Support.V4.App; using SMSDemo.Interfaces; using Android.Telephony; using System.Collections.Generic; using SMSDemo.Droid; using Xamarin.Forms;

    namespace SMSDemo.Droid { [Activity(Label = "Notificaciones", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Locked)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity,ISendMessage { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
    
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
    
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    
        public  void SendMessage(string phoneNumber, string content)
        {
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.SendSms) == Permission.Granted)
            {
                SmsManager smsManager = SmsManager.Default;
                // Split text message content (SMS length limit)
                IList<string> divideContents = smsManager.DivideMessage(content);
    
                foreach (string text in divideContents)
                {
                    smsManager.SendTextMessage(phoneNumber, null, text, null, null);
                }
            }
            else
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.SendSms }, 1);
            }
        }
    }
    

    }

    //////// My Page1 in portable proyect

    using Android; using Android.Content.PM; using Android.Support.V4.App; using Android.Support.V4.Content; using Android.Telephony; using LSNotificacionesMovil.Interfaces; using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml;

    namespace LSNotificacionesMovil.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Page1 : ContentPage { private string phonenumber; private string content;

        public Page1()
        {
            InitializeComponent();
        }
    
        private async void BtnSendSMS_Clicked(object sender, EventArgs e)
        {
            DependencyService.Get<ISendMessage>().SendMessage("77778888", "aaa");                     
        }  
    }
    

    }

    //////// My interface (I put it in my portable proyect) using System; using System.Collections.Generic; using System.Text;

    namespace SMSDemo.Interfaces { public interface ISendMessage { void SendMessage(string phoneNumber, string content); } }

    I got this exception.

    Friday, November 1, 2019 11:09 AM
  • User76049 posted

    @SpontonLuciano

    You've been given two answers, you need to debug your own code.

    Friday, November 1, 2019 11:11 AM
  • User388951 posted

    @NMackay said: @SpontonLuciano

    You've been given two answers, you need to debug your own code.

    you are right I dont know why I checked it as "answered", sorry

    Friday, November 1, 2019 11:30 AM
  • User76049 posted

    @SpontonLuciano

    Save yourself some time and just use Xamarin Essentials to do this! https://docs.microsoft.com/en-us/xamarin/essentials/sms?context=xamarin/xamarin-forms

    Depends if you want this feature to be hidden, just highlighting this as an option

    Friday, November 1, 2019 11:48 AM