Cover Image for Send SMS in Android
112 views

Send SMS in Android

To send an SMS (Short Message Service) in an Android app, you can use the SMSManager class. Here’s a step-by-step guide on how to send an SMS in Android:

1. Add Permissions:

In your AndroidManifest.xml file, add the necessary permissions for sending SMS.

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

2. Request Permission (if targeting Android 6.0 and above):

If your app targets Android 6.0 (API level 23) or higher, you need to request the SEND_SMS permission at runtime. You can request it like this:

Java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_SEND_SMS);
        return;
    }
}

Make sure to handle the permission request result in the onRequestPermissionsResult method.

3. Send SMS:

You can send an SMS using the SmsManager class. Here’s an example of how to send an SMS when a button is clicked:

Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_SEND_SMS = 123;
    private EditText phoneNumberEditText, messageEditText;
    private Button sendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        phoneNumberEditText = findViewById(R.id.phoneNumberEditText);
        messageEditText = findViewById(R.id.messageEditText);
        sendButton = findViewById(R.id.sendButton);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendSMS();
            }
        });
    }

    private void sendSMS() {
        String phoneNumber = phoneNumberEditText.getText().toString();
        String message = messageEditText.getText().toString();

        if (!phoneNumber.isEmpty() && !message.isEmpty()) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNumber, null, message, null, null);
                Toast.makeText(this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
            } else {
                // Permission not granted, request it
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_SEND_SMS);
            }
        } else {
            Toast.makeText(this, "Please enter a phone number and message", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_SEND_SMS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                sendSMS();
            } else {
                Toast.makeText(this, "Permission denied. SMS not sent.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

In this example:

  • We create an OnClickListener for the “Send” button to call the sendSMS method.
  • In the sendSMS method, we retrieve the phone number and message from EditText fields.
  • We check if the SEND_SMS permission is granted. If not, we request it.
  • If the permission is granted, we use SmsManager to send the SMS and display a success message.

4. Layout XML:

Create an XML layout file for your activity. Here’s a simple example:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/phoneNumberEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Phone Number" />

    <EditText
        android:id="@+id/messageEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Message" />

    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>

5. Testing:

Run your app on a physical Android device or emulator. Enter a phone number and message, then click the “Send” button to send the SMS.

Make sure to handle permissions and permission requests correctly, especially for Android 6.0 and above.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS