Signup/Sign In

SMS in Android

In this lesson, we will learn how to send messages in Android. There are two ways to send SMS:

  1. Sending SMS through built-in SMS application
  2. Sending SMS through our own app

Let's learn and implement both the methods.

Sending SMS through built-in SMS application

When we use any built-in apps for our purpose, we use implicit intents. Similarly, for sending sms through built-in sms application, we will use implicit intent.(If you have not read about intents, please check its tutorial first).

First we need to create Uri class object as follows:

Uri uri = Uri.parse("smsto:987654321;988998998");

We need to send ACTION_SENDTO and uri as the parameter while creating an object of class Intent.

Intent I = new Intent(ACTION_VIEW,uri);

For sending the message content, we need to use putExtra() method. The first parameter i.e. tag should be "sms_body" only

i.putExtra("sms_body", "I love studytonight");

Finally, we need to call the startActivity() method to start the intent.

startActivity(i);

Here is the full logic for sending sms:

Uri uri = Uri.parse("smsto:987654321");
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", "I Love Studytonight");
startActivity(i);

Sending SMS directly from your app

Since you are sending sms directly from your app, you need to specify permission in your Android Manifest file, above the <application> tag.

<uses-permission android:name="android.permission.SEND_SMS"/> 

You need a SmsManager instance to send sms. To get an instance, you can use SmsManager.getDefault() method.

SmsManager sms = SmsManager.getDefault();

To send the message, you can use sendTextMessage() method which has 5 parameters as follows:

  • destinationAddress: You need to specify mobile number of the recipient.
  • ServiceCenterAddress: You need to specify service center address. You can use null for default Service Center Address.
  • text: You need to specify the content of your message.
  • sendIntent: You need to specify Pending Intent to invoke when the message is sent.
  • deliveryIntent: You need to specify the Pending Intent to invoke when the message has been delivered.
    sms.sendTextMessage("987654321",null,"I love studytonight",null,null);

Here is the full logic:

In AndroidManifest.xml

<uses-permission android:name="android.permission.SEND_SMS"/> 

In your java file

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("987654321",null,"I love studytonight",null,null);

Note: If you are using this feature on Android phones having Android Version 6.0 and above(Marshmallow and above), you need to ask for the permission in runtime also, along with specifying the permission in AndroidManifest file.(Please see runtime permissions in Android topic if you have not read it yet).