实现效果如下:(为了尽量使用最少的代码实现功能,界面十分简单,方便理解原理)
这边我输入短信内容为"252525"
图一 输入发送号码和指定内容
图二 第一条为收到的短信
下面介绍代码实现:
在manifest.xml中添加权限:(不同的手机操作系统不同,有的手机需要更多的权限,比如小米手机需要打开通知权限,不然操作系统不会允许app发送通知类短信)
<uses-permission android:name="android.permission.SEND_SMS" /> <!--发送短信-->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!--访问电话状态-->
<uses-permission android:name="android.permission.RECEIVE_SMS" /> <!--接收短信-->
<uses-permission android:name="android.permission.READ_SMS" /><!-- 读取短信内容-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
正常情况下只要添加一行权限:
<uses-permission android:name="android.permission.SEND_SMS" /> <!--发送短信-->
前端xml代码: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="请输入手机号码"
android:inputType="phone"
android:minHeight="48dp" />
<EditText
android:id="@+id/edContent1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="内容"
android:inputType="phone"
android:minHeight="48dp" />
<Button
android:id="@+id/bt_sendSMSS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
</LinearLayout>
预览界面:
图三 布局预览
后端代码 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() {
//判断Android版本是否大于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();
//已有权限
}
} else {
//API 版本在23以下
}
}
/**
* 注册权限申请回调
*
* @param requestCode 申请码
* @param permissions 申请的权限
* @param grantResults 结果
*/
@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);
}
}
//发送短信
private void sendSMSS() {
String content = edContent.getText().toString().trim();
String phone = edPhone.getText().toString().trim();
Log.d("手机",phone);
if (!isEmpty(content) && !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("发送状态","成功");
// 短信发送成功
} else {
Log.d("发送状态","失败");
// 短信发送失败
}
}
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "手机号或内容不能为空", Toast.LENGTH_SHORT).show();
return;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public static boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
在上面代码中发送短信运用smsManager类,最关键的发送短信的函数是manager.sendTextMessage(phone, null, content, null, null);
manager.sendTextMessage(destinationAddress,
scAddress,
text,
sentIntent,
deliveryIntent),其中destinationAddress指的是接受人,scAddress指的是短信中心服务号码,发送短信需要先转发到中心服务号码进而发送到收件人手机,这边只要设置为null,程序自动检测,text为发送短信的内容,sentIntent: 发送短信结果状态信号,deliveryIntent: 对方接收状态信号(是否已成功接收),都设置为null即可
上面用try-catch结构检测发送状态
如果不用广播监听发送状态的话写以上代码即可,发送失败则可以查看下方广播代码的编写:(以下为带广播的全部代码)
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:
// 短信发送成功
Log.e("signal","成功");
Toast.makeText(context, "短信发送成功yyyyy", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
// 短信发送失败
Log.e("signal","失败");
Toast.makeText(context, "短信发送失败", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
// 手机没有信号,无法发送短信
Log.e("signal","失败");
Toast.makeText(context, "手机无信号,无法发送短信", Toast.LENGTH_SHORT).show();
break;
// 更多其他错误码可根据需要进行处理
}
}
};
@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() {
//判断Android版本是否大于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();
//已有权限
}
} else {
//API 版本在23以下
}
}
/**
* 注册权限申请回调
*
* @param requestCode 申请码
* @param permissions 申请的权限
* @param grantResults 结果
*/
@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);
}
}
//发送短信
private void sendSMSS() {
String content = edContent.getText().toString().trim();
String phone = edPhone.getText().toString().trim();
Log.d("手机",phone);
if (!isEmpty(content) && !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("发送状态","成功");
// 短信发送成功
} else {
Log.d("发送状态","失败");
// 短信发送失败
}
}
Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "手机号或内容不能为空", Toast.LENGTH_SHORT).show();
return;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册广播接收器
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);这两行代码为注册广播
在manager.sendTextMessage(phone, null, content, sentPendingIntent, null);中将第四个参数设置为sentPendingIntent
效果:getResultCode()的值为-1是发送成功的状态
图四 控制台截图
注意:状态为-1不一定等于你一定能够收到短信,以手机收到实际短信为准,仔细检查手机给予app的权限,可以把相关权限都开启,包括通知权限以及发送短消息的权限,不是所有手机都会自动跳出弹窗询问是否开启某项权限的!!可以考虑换机子尝试,smsmanager是用手机默认手机号发送短信的
在Android中,使用SmsManager
发送短信并不意味着短信一定会立即被接收到。短信的传递是由运营商网络来处理的,可能会有延迟或其他因素导致短信无法立即到达目标手机号码。
此外,还有一些常见的问题可能导致短信发送成功但未收到短信的情况:
-
权限问题:确保你的应用已经获得了发送短信的权限(
Manifest.permission.SEND_SMS
)并且用户已经授予了该权限。 -
目标手机号码正确性:确认你正在发送短信的目标手机号码是正确的,确保手机号码格式正确且有效。
-
网络连接问题:确保你的设备处于正常的移动网络或Wi-Fi连接状态,以便发送短信。
-
运营商限制:有些运营商可能对短信进行限制,例如在某些国家/地区可能需要预先注册短信服务或开通特定的短信套餐。文章来源:https://www.toymoban.com/news/detail-763817.html
如果你仍然无法解决问题,建议你尝试使用其他方法发送短信,例如使用第三方的短信服务提供商或者调用运营商的短信发送接口。文章来源地址https://www.toymoban.com/news/detail-763817.html
到了这里,关于Android发送短信最简单代码实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!