sid*_*art 4 telephonymanager flutter
我正在使用电话依赖项receive_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'))
],
),
));
}
}
Run Code Online (Sandbox Code Playgroud)
我确保在 Android Manifest 文件中添加了正确的权限。我请求了RECEIVE_SMS和BROADCAST_SMS权限,它似乎正在工作,因为我可以在模拟器中接收消息。
我究竟做错了什么?
在开始收听消息之前尝试请求许可。
bool permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
Run Code Online (Sandbox Code Playgroud)
这里列出了所需的许可以及如何请求。
https://telephony.shoutakmulay.dev/permissions
| 归档时间: |
|
| 查看次数: |
1139 次 |
| 最近记录: |