Sending an SMS message is a common feature in many applications. Whether it’s for two-factor authentication, notifications, or communication, SMS functionality can greatly enhance the user experience. In this blog post, we’ll explore how to send SMS messages in Android using SmsManager
.
Step 1: Setting Up the SmsManager
The first step in sending an SMS using Android is to set up an SmsManager
. SmsManager
is a class that provides access to the system SMS service.
Here’s a simple example of how to create an SmsManager
:
SmsManager smsManager = SmsManager.getDefault();
In this code, SmsManager.getDefault()
is used to get the default instance of the SmsManager
.
Step 2: Sending the SMS
Once the SmsManager
is set up, we can use it to send an SMS. This is done using the sendTextMessage
method, which takes five parameters: the destination address, the source address, the text to send, a PendingIntent
to perform when the message is sent, and a PendingIntent
to perform when the message is delivered.
Here’s how to send an SMS:
String phoneNumber = "1234567890";
String message = "Hello, World!";
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
In this code, phoneNumber
is the phone number to send the SMS to, and message
is the text of the SMS. The second parameter is the service center address, but it’s usually null
. The last two parameters are PendingIntents
that are used to perform actions when the SMS is sent and delivered, but they can be null
if you don’t need to perform any actions.
Step 3: Handling Permissions
To send an SMS, your app needs the SEND_SMS
permission. This should be declared in your app’s manifest file like this:
<uses-permission android:name="android.permission.SEND_SMS" />
Additionally, starting from Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app’s functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app’s Settings screen.
Here’s how to request the SEND_SMS
permission at runtime:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS);
}
In this code, ContextCompat.checkSelfPermission
is used to check if the app has the SEND_SMS
permission, and ActivityCompat.requestPermissions
is used to request permission if it’s not already granted. MY_PERMISSIONS_REQUEST_SEND_SMS
is a constant that’s used as the request code for the permission request.