蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

10.2 SmsManager(短信管理器)

核对 Android 发送文字短信的两大路径(零权限系统 ACTION_SENDTO 短信页与 SmsManager 直接接口)、GSM-7(160/153)与 UCS-2(70/67)长短信拆分规律、sentIntent/deliverIntent 广播状态码及运行时权限约束。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

路径一:通过 ACTION_SENDTO 唤起系统短信界面

`SmsManager` 专用于管理普通文字短信的发送与状态追踪。业务需要发送短信时,最优先且用户体验最佳的方案并非直接调用底层接口,而是通过 `PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)` 校验号码合法性后,构造 `new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber))` 并附带 `intent.putExtra("sms_body", message)` 跳转至系统默认短信应用。该方式完全不需要声明 `SEND_SMS` 敏感权限,既避免了安装/运行时的权限顾虑与系统拦截,也让用户在点击发送前能够核对收件人与文案。

路径二:SmsManager 直接发信、长短信拆分与状态广播

若业务确需静默直发(如特定企业/工具类应用),则须在 `AndroidManifest.xml` 中声明 `<uses-permission android:name="android.permission.SEND_SMS"/>`(Android 6.0+ 须动态申请运行时危险权限,且上架应用商店受严格政策审核)。调用 `SmsManager.getDefault()`(API 31+ 推荐 `context.getSystemService(SmsManager.class)`)后,先用 `divideMessage(message)` 拆分长文本,再逐段调用 `sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliverIntent)`(或直接调用 `sendMultipartTextMessage`)。其五个参数依次为收件人号码、短信中心号码(传 `null` 使用默认)、正文、发送状态 `PendingIntent`(成功返回 `Activity.RESULT_OK`,失败返回 `RESULT_ERROR_GENERIC_FAILURE`/`RESULT_ERROR_RADIO_OFF`/`RESULT_ERROR_NULL_PDU`/`RESULT_ERROR_NO_SERVICE`)以及对方送达回执 `PendingIntent`(附带 `"pdu"` 协议数据单元)。需精确核算长短信编码阈值(本站实验已验证):纯 GSM-7 字符单条上限 **160** 字符,超长拆分后因占用 7 字节 UDH 拼接头,每段上限降为 **153** 字符;含中文等 UCS-2 字符单条上限 **70** 字,超长拆分后每段上限降为 **67** 字(140 个汉字会拆成 `67 + 67 + 6` 共 3 条)。

要实时捕获发送结果与对方送达状态,可分别为自定义广播动作 `"SENT_SMS_ACTION"` 与 `"DELIVERED_SMS_ACTION"` 创建 `PendingIntent.getBroadcast(...)` 并动态 `registerReceiver(...)` 监听(Android 12 / API 31+ 必须为 `PendingIntent` 显式传入 `FLAG_IMMUTABLE` 或 `FLAG_MUTABLE`,Android 14+ 动态注册应用内广播还需指定 `RECEIVER_NOT_EXPORTED`,并在页面销毁时及时 `unregisterReceiver` 防泄漏;广播基础可参见前序 `BroadcastReceiver` 章节)。综上,非强定制场景仍首选路径一。

运行离线 SmsManager 零权限 Intent、GSM-7(160/153) 与 UCS-2(70/67) 拆分及状态码核验

python · 阅读源码
"""Offline Android system-service verifier for Ch 137: SmsManager & Multipart SMS Splitting."""
import json
import re

VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"

GSM7_BASIC = set(
    "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?"
    "¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà"
)


def is_global_phone_number(num: str) -> bool:
    return bool(re.fullmatch(r"\+?[0-9\-\s()]{3,20}", num.strip()))


def divide_sms_message(text: str) -> dict:
    # GSM-7: 160 chars single, 153 chars per multipart segment (7-byte UDH)
    # UCS-2 (Chinese/non-GSM7): 70 chars single, 67 chars per multipart segment (6-byte UDH)
    is_gsm7 = all(ch in GSM7_BASIC for ch in text)
    encoding = "GSM-7" if is_gsm7 else "UCS-2"
    single_limit = 160 if is_gsm7 else 70
    multi_limit = 153 if is_gsm7 else 67
    if len(text) <= single_limit:
        parts = [text]
    else:
        parts = [text[i : i + multi_limit] for i in range(0, len(text), multi_limit)]
    return {
        "encoding": encoding,
        "length": len(text),
        "single_limit": single_limit,
        "multi_limit": multi_limit,
        "part_count": len(parts),
        "part_lengths": [len(p) for p in parts],
    }


def main() -> None:
    # Case 1: System SMS Intent (ACTION_SENDTO + smsto: + sms_body) with PhoneNumberUtils validation
    valid_nums = [is_global_phone_number(n) for n in ("13800138000", "+8613800138000", "abc")]
    intent_spec = {
        "action": "android.intent.action.SENDTO",
        "data_uri": "smsto:13800138000",
        "extra_key": "sms_body",
        "requires_send_sms_permission": False,
    }
    c1_actual = {
        "phone_validations": valid_nums,
        "intent_spec": intent_spec,
    }
    c1_expected = {
        "phone_validations": [True, True, False],
        "intent_spec": {
            "action": "android.intent.action.SENDTO",
            "data_uri": "smsto:13800138000",
            "extra_key": "sms_body",
            "requires_send_sms_permission": False,
        },
    }

    # Case 2: GSM-7 160-char single vs 161-char -> 2 parts (153 + 8)
    gsm_160 = divide_sms_message("A" * 160)
    gsm_161 = divide_sms_message("A" * 161)
    c2_actual = {
        "gsm_160": [gsm_160["encoding"], gsm_160["part_count"], gsm_160["part_lengths"]],
        "gsm_161": [gsm_161["encoding"], gsm_161["part_count"], gsm_161["part_lengths"]],
    }
    c2_expected = {
        "gsm_160": ["GSM-7", 1, [160]],
        "gsm_161": ["GSM-7", 2, [153, 8]],
    }

    # Case 3: UCS-2 (Chinese) 70-char single vs 140-char -> 3 parts (67 + 67 + 6)
    ucs_70 = divide_sms_message("中" * 70)
    ucs_140 = divide_sms_message("中" * 140)
    c3_actual = {
        "ucs_70": [ucs_70["encoding"], ucs_70["part_count"], ucs_70["part_lengths"]],
        "ucs_140": [ucs_140["encoding"], ucs_140["part_count"], ucs_140["part_lengths"]],
    }
    c3_expected = {
        "ucs_70": ["UCS-2", 1, [70]],
        "ucs_140": ["UCS-2", 3, [67, 67, 6]],
    }

    # Case 4: sentIntent & deliverIntent result codes + API 23/31 permission & PendingIntent immutability
    sent_codes = {
        "RESULT_OK": -1,
        "RESULT_ERROR_GENERIC_FAILURE": 1,
        "RESULT_ERROR_RADIO_OFF": 2,
        "RESULT_ERROR_NULL_PDU": 3,
        "RESULT_ERROR_NO_SERVICE": 4,
    }
    c4_actual = {
        "sent_result_codes": sent_codes,
        "send_sms_dangerous_permission_api23": True,
        "api31_smsmanager_lookup": "context.getSystemService(SmsManager.class)",
        "api31_pending_intent_flag_required": "PendingIntent.FLAG_IMMUTABLE",
    }
    c4_expected = {
        "sent_result_codes": {
            "RESULT_OK": -1,
            "RESULT_ERROR_GENERIC_FAILURE": 1,
            "RESULT_ERROR_RADIO_OFF": 2,
            "RESULT_ERROR_NULL_PDU": 3,
            "RESULT_ERROR_NO_SERVICE": 4,
        },
        "send_sms_dangerous_permission_api23": True,
        "api31_smsmanager_lookup": "context.getSystemService(SmsManager.class)",
        "api31_pending_intent_flag_required": "PendingIntent.FLAG_IMMUTABLE",
    }

    cases = [
        {
            "name": "sms_intent_sendto_and_phone_validation",
            "summary": "核验 ACTION_SENDTO + smsto: 零权限系统短信页调用与合法手机号校验",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "sms_divide_message_gsm7_160_153",
            "summary": "核验 GSM-7 编码短信单条 160 字符上限及超长后按 153 字符/段(含 UDH)拆分规则",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "sms_divide_message_ucs2_70_67",
            "summary": "核验中文 UCS-2 短信单条 70 字上限及 140 汉字按 67 字/段拆分为 3 段(67+67+6)",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "sms_pending_intent_codes_and_runtime_perm",
            "summary": "核验 sentIntent 5 项结果码、API 23 SEND_SMS 运行时权限及 API 31 FLAG_IMMUTABLE 要求",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 smsto: URI 校验、160/161 字符 GSM-7 拆分、70/140 汉字 UCS-2 三段拆分及 5 项 sentIntent 结果码与 API 31 规范。
运行离线 SmsManager 零权限 Intent、GSM-7(160/153) 与 UCS-2(70/67) 拆分及状态码核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:5dbb059ada91ff29155f920fa4324b3b711619161fd82675a51bcf38e245364b

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载10.2 SmsManager(短信管理器)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:fa4115f4aa9cb5a40a4bd617a8d6a41edc2348cdb7ba4a186fa2f5e481ac7d18

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

使用 `SmsManager.divideMessage()` 拆分一条包含 140 个汉字的长短信时,为什么不是拆成 2 条(70+70)而是 3 条(67+67+6)?

展开参考解答

单条 UCS-2 短信最多容纳 70 个字符;一旦超过 70 字进入长短信拼接模式,每条分片都必须预留 6 字节(相当于 3 个 UCS-2 字符)存放 UDH 拼接序号头,因此每段有效容量降至 67 字,140 字需拆为 `67 + 67 + 6` 共 3 段。

规范与官方依据