Flutter Telephony插件真机无法接收SMS仅模拟器可用问题排查
问题
我使用telephony依赖实现receive_sms功能,该功能在模拟器中可正常接收所有消息,但在真实硬件手机上无法工作。
我已确保Android Manifest文件中添加了正确的权限,申请了RECEIVE_SMS和BROADCAST_SMS权限,且模拟器中可正常接收消息,请问我哪里操作有误?
以下是我的代码:
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:telephony/telephony.dart'; onBackgroundMessage(SmsMessage message) { debugPrint("onBackgroundMessage called"); } void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _message = ""; final telephony = Telephony.instance; @override void initState() { super.initState(); initPlatformState(); } onMessage(SmsMessage message) async { setState(() { _message = message.body ?? "Error reading message body."; }); } onSendStatus(SendStatus status) { setState(() { _message = status == SendStatus.SENT ? "sent" : "delivered"; }); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initPlatformState() async { // Platform messages may fail, so we use a try/catch PlatformException. // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. final bool? result = await telephony.requestPhoneAndSmsPermissions; if (result != null && result) { telephony.listenIncomingSms( onNewMessage: onMessage, onBackgroundMessage: onBackgroundMessage); } if (!mounted) return; } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center(child: Text("Latest received SMS: $_message")), TextButton( onPressed: () async { await telephony.openDialer("123413453"); }, child: Text('Open Dialer')) ], ), )); } }
排查与解决要点
- 默认短信应用设置:Android 4.4及以上版本,只有默认短信应用能接收完整的SMS广播。进入手机「设置-应用-默认应用-短信」,把你的App设为默认短信应用后再测试,验证是否是权限限制导致的问题。
- 权限有效性验证:虽然调用了
requestPhoneAndSmsPermissions,但可以在initPlatformState里添加权限状态检查,比如用await telephony.checkPermissionStatus确认权限是否真的被授予,避免权限请求失败但代码未处理的情况。 - 后台运行权限:小米、华为、OPPO等厂商有严格的后台管理策略,会限制App后台接收广播。去手机设置给你的App开启「后台运行权限」「忽略电池优化」,防止系统杀死进程导致无法接收短信。
- 后台消息监听规则:
onBackgroundMessage是隔离函数,不能直接调用UI相关方法(比如setState),需确保该函数逻辑符合后台运行要求;同时检查AndroidManifest中是否有插件自动注册的广播接收器,避免配置遗漏。 - 短信类型测试:部分真实手机会优先拦截验证码、服务类短信,优先交给系统自带短信应用处理。可以尝试发送普通文本短信测试,排除系统过滤规则的影响。
- 插件版本适配:确认telephony插件版本和当前Flutter、Android SDK版本兼容,尝试升级到最新稳定版,修复版本不兼容带来的问题。
内容的提问来源于stack exchange,提问作者sid heart
相关产品推荐
相关产品推荐

