Flutter中使用Telephony包无法直接发送SMS问题求助
Flutter Telephony包直接发送SMS失败的解决方法
问题描述
使用Flutter的Telephony包发送短信时,sendSmsByDefaultApp()方法可正常通过默认短信应用发送,但直接调用sendSms()从应用内发送则失败。已添加相关权限,代码及权限配置如下:
代码示例:
import 'package:flutter/material.dart'; import 'package:telephony/telephony.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: ElevatedButton( onPressed: () { sendSMS(); }, child: Text("Send SMS"), ), ), ), ); } void sendSMS() async { final Telephony telephony = Telephony.instance; bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions; print(permissionsGranted); await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message."); print("SMS Sent"); } }
已添加的权限:
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
解决步骤
- 确认权限真正授予
仅调用requestPhoneAndSmsPermissions不代表权限一定被用户授予,需在发送前二次校验权限状态:
bool hasSmsPermission = await telephony.checkPermission(SmsPermission.SEND_SMS); if (!hasSmsPermission) { bool? permissionsGranted = await telephony.requestPhoneAndSmsPermissions; hasSmsPermission = await telephony.checkPermission(SmsPermission.SEND_SMS); if (!hasSmsPermission) { print("短信权限未授予,无法发送"); return; } }
- 捕获发送异常排查原因
原代码未处理发送时的异常,添加try-catch捕获错误信息,便于定位问题:
try { await telephony.sendSms(to: "+92xxxxxxxxxx", message: "Hello, this is a test message."); print("SMS Sent"); } catch (e) { print("发送失败详情: $e"); }
- 适配Android 12+权限
Android 12及以上版本,需额外添加通知权限(部分设备上Telephony包依赖此权限发送状态通知):
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
检查设备权限设置
部分厂商设备会限制第三方应用直接发送短信,需前往系统设置→应用管理→你的应用→权限,确认发送短信权限已开启。更新Telephony包至最新版本
旧版本可能存在已知bug,执行flutter pub upgrade telephony更新到最新版。
内容的提问来源于stack exchange,提问作者umair alam
相关产品推荐
相关产品推荐

