当前位置:首页 > 行业动态 > 正文

安卓发送短信 并记录

安卓用SMSManager发短信,记录可存数据库或文件

权限配置

安卓发送短信需要申请敏感权限,需在AndroidManifest.xml中声明:

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

注意:Android 6.0+需动态申请权限,否则会触发SecurityException

安卓发送短信 并记录  第1张

发送短信核心代码

使用SmsManager发送短信,并通过PendingIntent监听发送状态:

// 获取SmsManager实例
SmsManager smsManager = SmsManager.getDefault();
// 分割长短信(可选)
ArrayList<String> messageList = smsManager.divideMessage("测试短信内容");
// 创建发送状态监听器
PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, 
    new Intent(SENT_SMS_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);
// 发送短信
smsManager.sendTextMessage("1234567890", null, messageList.get(0), sentIntent, null);
// 广播接收器处理发送结果
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Log.d("SMS", "发送成功");
                break;
            default:
                Log.d("SMS", "发送失败");
                break;
        }
    }
};
IntentFilter filter = new IntentFilter(SENT_SMS_ACTION);
context.registerReceiver(receiver, filter);

记录发送日志

本地日志记录(推荐)

// 写入文件
File logFile = new File(context.getExternalFilesDir(null), "sms_log.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
writer.write("发送时间:" + System.currentTimeMillis() + ", 目标号码:1234567890
");
writer.close();

数据库记录(适合长期存储)

-创建表
CREATE TABLE sms_record (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    phone TEXT,
    content TEXT,
    time INTEGER,
    status INTEGER
);
// 插入数据
ContentValues values = new ContentValues();
values.put("phone", "1234567890");
values.put("content", "测试短信");
values.put("time", System.currentTimeMillis());
values.put("status", getResultCode()); // 来自广播返回码
DatabaseUtils.insert(db, "sms_record", values);

注意事项

  1. Android 11+限制:需用户手动在设置中开启”允许该应用发送短信”权限。
  2. 双卡手机适配:需指定SubscriptionManager选择SIM卡。
  3. 隐私合规:需在隐私政策中声明短信权限用途。

实现方式对比表

实现方式 优点 缺点
SmsManager 系统原生API,兼容性好 无法自定义发送界面
隐式Intent 可调用第三方短信应用 需处理多种返回结果,兼容性差
第三方库(如EasySMS) 功能扩展性强 增加APK体积,存在兼容性风险

相关问题与解答

Q1:用户拒绝短信权限如何处理?

A:应弹出对话框解释权限必要性,并提供跳转至设置页面的入口:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_CODE);
} else {
    // 执行发送逻辑
}

Q2:如何将发送记录同步到远程服务器?

A:可在onReceive中封装HTTP请求:

OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
    .add("phone", "1234567890")
    .add("status", String.valueOf(getResultCode()))
    .build();
Request request = new Request.Builder()
    .url("https://yourserver.com/api/sms_log")
    .post(body)
    .build();
client.newCall(request).enqueue(new Callback() {...});
0