效果图
代码实现
先添加权限
<!-- 允许程序发送SMS短信 --> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <!-- 允许程序读取短信息 --> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <!-- 允许程序监控一个将收到短信息,记录或处理 --> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
.java
由用户输入手机号 自定义短信内容
/** * 由用户输入手机号 * @param message:短信内容 */ private void send(String message) { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", message); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent); }
跳转系统发送短信页面 自定义手机号短信内容
/** * 跳转系统发送短信页面 * * @param phone:手机号 * @param message:短信内容 */ private void sendSms(String phone, String message) { Uri uri = Uri.parse("smsto:" + phone); Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri); sendIntent.putExtra("sms_body", message); startActivity(sendIntent); }
全部代码
package top.gaojc.sendsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button btSendSms; private final String PHONE = "173011201164"; private final String MESSAGE = "你好"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btSendSms = findViewById(R.id.bt_send_sms); btSendSms.setOnClickListener(v -> { send(MESSAGE); }); } /** * 由用户输入手机号 * @param message:短信内容 */ private void send(String message) { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", message); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent); } /** * 跳转系统发送短信页面 * * @param phone:手机号 * @param message:短信内容 */ private void sendSms(String phone, String message) { Uri uri = Uri.parse("smsto:" + phone); Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri); sendIntent.putExtra("sms_body", message); startActivity(sendIntent); } }
.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/bt_send_sms" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送短信" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>