renderings
Code
Add permissions first
<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
Customize text message content by user inputting mobile phone number
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);
}
Jump to the system to send SMS page to customize the text message content of mobile phone number
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);
}
All code
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);
});
}
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);
}
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>