The simplest code implementation for Android to send SMS

The implementation effect is as follows: (In order to use the least code to realize the function as much as possible, the interface is very simple and easy to understand the principle)

Here I enter the SMS content as “252525”

Figure 1 Enter the sending number and specified content

Figure 2 The first message is the received text message

The code implementation is introduced below:

Add permissions in manifest.xml: (different phone operating systems are different, some phones need more permissions, for example, Xiaomi phones need to enable notification permissions, otherwise the operating system will not allow the app to send notification messages)

 <uses-permission android:name="android.permission.SEND_SMS" /> <!--Send SMS-->
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!--Access phone status-->

    <uses-permission android:name="android.permission.RECEIVE_SMS" /> <!--Receive SMS-->
    <uses-permission android:name="android.permission.READ_SMS" /><!-- read SMS content -->

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

Normally, you only need to add one line of permissions:

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

Front-end xml code: activity_main.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:gravity="center"
    android:orientation="vertical">

    <EditText
        android:id="@ + id/edPhone1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Please enter your phone number"
        android:inputType="phone"
        android:minHeight="48dp" />

    <EditText
        android:id="@ + id/edContent1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="content"
        android:inputType="phone"
        android:minHeight="48dp" />

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

</LinearLayout>

Preview interface:

Figure 3 Layout preview

Backend code MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private EditText edContent;
    private EditText edPhone;

    private static final int SEND_SMS = 100;


    private static final String SMS_SENT_ACTION = "SMS_SENT";


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

        edContent = findViewById(R.id.edContent1);
        edPhone = findViewById(R.id.edPhone1);
        Button btSend = findViewById(R.id.bt_sendSMSS);
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
    }




    private void requestPermission() {
        //Determine whether the Android version is greater than 23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager. PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS);
                return;
            } else {
                sendSMSS();
                // Already have permission
            }
        } else {
            //API version is below 23
        }
    }

    /**
     * Registration permission application callback
     *
     * @param requestCode application code
     * @param permissions application permissions
     * @param grantResults result
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case SEND_SMS:
                if (grantResults[0] == PackageManager. PERMISSION_GRANTED) {
                    sendSMSS();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "SEND_SMS Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //send messages
    private void sendSMSS() {
        String content = edContent.getText().toString().trim();
        String phone = edPhone.getText().toString().trim();
        Log.d("Mobile phone",phone);
        if (!isEmpty(content) & amp; & amp; !isEmpty(phone)) {
            SmsManager manager = SmsManager. getDefault();
            ArrayList<String> strings = manager. divideMessage(content);
            for (int i = 0; i < strings. size(); i ++ ) {
                boolean isMessageSent = false;
                try {
                    manager. sendTextMessage(phone, null, content, null, null);
                    isMessageSent = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (isMessageSent) {
                    Log.d("Sending Status","Success");
                    // SMS sent successfully
                } else {
                    Log.d("Sending Status","Failure");
                    // message failed to send
                }

            }
            Toast.makeText(MainActivity.this, "sent successfully", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "The phone number or content cannot be empty", Toast.LENGTH_SHORT).show();
            return;
        }

    }
    @Override
    protected void onDestroy() {
        super. onDestroy();

    }

    public static boolean isEmpty(String str) {

        return str == null || str.trim().isEmpty();
    }
}

In the above code, the smsManager class is used to send text messages. The most critical function for sending text messages is manager.sendTextMessage(phone, null, content, null, null);

manager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent), where destinationAddress refers to the recipient , scAddress refers to the service number of the SMS center. To send a text message, it needs to be forwarded to the center service number and then sent to the recipient’s mobile phone. As long as it is set to null, the program will automatically detect it. text is the content of the text message sent. sentIntent: the result of sending the text message Status signal, deliveryIntent: The other party receives the status signal (whether it has been successfully received), all of which can be set to null

The above uses the try-catch structure to detect the sending status

If you don’t need to broadcast to monitor the sending status, you can write the above code. If the sending fails, you can check the writing of the broadcast code below: (the following are all codes with broadcast)

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android. content. Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText edContent;
    private EditText edPhone;

    private static final int SEND_SMS = 100;


    private static final String SMS_SENT_ACTION = "SMS_SENT";




    private BroadcastReceiver smsSentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("MyBroadcastReceiver", "Received broadcast: " + intent.getAction());
            Log.d("code", String.valueOf(getResultCode()));
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    // SMS sent successfully
                    Log.e("signal","success");
                    Toast.makeText(context, "SMS sent successfully yyyyy", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    // message failed to send
                    Log.e("signal","failed");
                    Toast.makeText(context, "SMS sending failed", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    // The mobile phone has no signal and cannot send SMS
                    Log.e("signal","failed");
                    Toast.makeText(context, "The phone has no signal and cannot send text messages", Toast.LENGTH_SHORT).show();
                    break;
                // More other error codes can be processed as needed
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R. layout. activity_main);

        edContent = findViewById(R.id.edContent1);
        edPhone = findViewById(R.id.edPhone1);
        Button btSend = findViewById(R.id.bt_sendSMSS);
        registerReceiver(smsSentReceiver, new IntentFilter(SMS_SENT_ACTION));
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
    }




    private void requestPermission() {
        //Determine whether the Android version is greater than 23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager. PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS);
                return;
            } else {
                registerReceiver(smsSentReceiver, new IntentFilter(SMS_SENT_ACTION));
                sendSMSS();
                // Already have permission
            }
        } else {
            //API version is below 23
        }
    }

    /**
     * Registration permission application callback
     *
     * @param requestCode application code
     * @param permissions application permissions
     * @param grantResults result
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case SEND_SMS:
                if (grantResults[0] == PackageManager. PERMISSION_GRANTED) {
                    sendSMSS();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "SEND_SMS Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //send messages
    private void sendSMSS() {
        String content = edContent.getText().toString().trim();
        String phone = edPhone.getText().toString().trim();
        Log.d("Mobile phone",phone);
        if (!isEmpty(content) & amp; & amp; !isEmpty(phone)) {
            SmsManager manager = SmsManager. getDefault();

            Intent sentIntent = new Intent(SMS_SENT_ACTION);
            PendingIntent sentPendingIntent = PendingIntent.getBroadcast(this, 0, sentIntent, PendingIntent.FLAG_IMMUTABLE);
            

            ArrayList<String> strings = manager. divideMessage(content);
            for (int i = 0; i < strings. size(); i ++ ) {
                boolean isMessageSent = false;
                try {
                    manager.sendTextMessage(phone, null, content, sentPendingIntent, null);
                    isMessageSent = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (isMessageSent) {
                    Log.d("Sending Status","Success");
                    // SMS sent successfully
                } else {
                    Log.d("Sending Status","Failure");
                    // message failed to send
                }


            }
            Toast.makeText(MainActivity.this, "sent successfully", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "The phone number or content cannot be empty", Toast.LENGTH_SHORT).show();
            return;
        }

    }
    @Override
    protected void onDestroy() {
        super. onDestroy();

        // unregister the broadcast receiver
        unregisterReceiver(smsSentReceiver);
    }
    public static boolean isEmpty(String str) {

        return str == null || str.trim().isEmpty();
    }
}

Intent sentIntent = new Intent(SMS_SENT_ACTION);
PendingIntent sentPendingIntent = PendingIntent.getBroadcast(this, 0, sentIntent, PendingIntent.FLAG_IMMUTABLE); These two lines of code are registered broadcasts

In manager.sendTextMessage(phone, null, content, sentPendingIntent, null); set the fourth parameter to sentPendingIntent

Effect: The value of getResultCode() is -1, which means the sending is successful

Figure 4 Console Screenshot

Note: A status of -1 does not necessarily mean that you will be able to receive text messages. The actual text messages received by the mobile phone shall prevail. Carefully check the permissions given by the mobile phone to the app. You can enable all relevant permissions, including notification permissions and sending short messages permissions, not all mobile phones will automatically pop up a pop-up window asking whether to open a certain permission! ! You can consider trying to change the phone, smsmanager uses the default phone number of the phone to send text messages

In Android, using SmsManager to send a text message does not mean that the text message will be received immediately. The delivery of the SMS is handled by the carrier network, there may be delays or other factors that prevent the SMS from reaching the target mobile number immediately.

In addition, there are some common problems that may cause the SMS to be sent successfully but not received:

  1. Permission issues: Make sure your application has the permission to send SMS (Manifest.permission.SEND_SMS) and the user has granted this permission.

  2. The correctness of the target mobile phone number: Confirm that the target mobile phone number you are sending SMS is correct, and ensure that the format of the mobile phone number is correct and valid.

  3. Network connectivity issues: Make sure your device is on a working mobile network or Wi-Fi connection in order to send text messages.

  4. Carrier restrictions: Some carriers may impose restrictions on text messages, for example, in some countries/regions, you may need to pre-register for SMS service or subscribe to a specific SMS package.

If you still can’t solve the problem, it is recommended that you try to use other methods to send SMS, such as using a third-party SMS service provider or calling the operator’s SMS sending interface.