使用 Intent.ACTION_VIEW 配合 smsto: URI 呼喚系統短信界面,發現 putExtra("sms_body", ...) 可預填內容,但號碼無法通過 URI 傳遞到目標應用。
Uri smsToUri = Uri.parse("smsto:123456");
Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
sendIntent.putExtra("sms_body", "Hello dear world");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
不同廠商短信應用對 smsto: URI 解析不一致,部分不解析 URI 中的號碼。標準做法是額外通過 Extra 傳遞 address 字段。
public void sendSms(String phoneNumber, String content) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
intent.putExtra("sms_body", content);
// 關鍵:額外設置 address,兼容更多短信應用
intent.putExtra("address", phoneNumber);
// 可選:指定 MIME 類型
// intent.setType("vnd.android-dir/mms-sms");
// 檢查是否有應用處理
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "未找到短信應用", Toast.LENGTH_SHORT).show();
}
}
| Action | URI Scheme | 權限 | 行為 | 推薦度 |
|---|---|---|---|---|
| ACTION_SENDTO | smsto:/sms:/mms: | 無 | 打開短信編輯界面,預填內容,用戶確認發送 | ⭐⭐⭐⭐⭐ |
| ACTION_SEND | 無 | 無 | 系統分享選單,用戶選擇短信/微信/郵件等 | ⭐⭐⭐⭐ |
| ACTION_VIEW | content://sms/ | READ_SMS | 查看短信會話列表 | ⭐⭐ |
| ACTION_SEND (MMS) | 無 | 無 | 發送彩信,支持附件 | ⭐⭐⭐ |
public class SmsUtils {
public static void openSmsCompose(Context context, String phoneNumber, String body) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
intent.putExtra("sms_body", body);
intent.putExtra("address", phoneNumber); // 兼容性關鍵
// 部分舊設備需要
intent.putExtra("exit_on_sent", true);
if (intent.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(intent);
} else {
// 降級:ACTION_SEND
Intent fallback = new Intent(Intent.ACTION_SEND);
fallback.putExtra("address", phoneNumber);
fallback.putExtra("sms_body", body);
fallback.setType("vnd.android-dir/mms-sms");
if (fallback.resolveActivity(context.getPackageManager()) != null) {
context.startActivity(fallback);
} else {
Toast.makeText(context, "無可用短信應用", Toast.LENGTH_SHORT).show();
}
}
}
// 直接發送短信 (需 SEND_SMS 權限,不彈界面)
public static void sendSmsDirect(Context context, String phoneNumber, String body) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
// 長短信自動分割
List parts = smsManager.divideMessage(body);
for (String part : parts) {
smsManager.sendTextMessage(phoneNumber, null, part, null, null);
}
} else {
// 請求權限邏輯...
}
}
}
ACTION_SENDTO / ACTION_SEND:無需權限,用戶確認發送SmsManager.sendTextMessage:需 SEND_SMS 危險權限 (Android 6.0+ 需動態申請),靜默發送READ_SMS 權限PhoneNumberUtils.formatNumber() 格式化