Flutter短信接收插件easy_sms_receiver的使用
Flutter短信接收插件easy_sms_receiver的使用
easy_sms_receiver
easy_sms_receiver
是一个Flutter插件,用于在Android平台上监听和读取传入的SMS。
使用方法
要在项目中使用此插件,需要在 pubspec.yaml
文件中添加 easy_sms_receiver
作为依赖项。
dependencies:
easy_sms_receiver: ^0.0.1
此外,还需要添加 permission_handler
和 flutter_background_service
作为依赖项,以便请求SMS权限并在后台监听传入的SMS。
dependencies:
permission_handler: ^10.0.0
flutter_background_service: ^1.5.0
设置
导入 easy_sms_receiver
包
import 'package:easy_sms_receiver/easy_sms_receiver.dart';
获取 easy_sms_receiver
的单例实例
final EasySmsReceiver easySmsReceiver = EasySmsReceiver.instance;
权限
此插件需要SMS权限才能读取传入的SMS。因此,需要使用 permission_handler
请求SMS权限:
final permissionStatus = await Permission.sms.request();
注意:插件只会请求在 AndroidManifest.xml
中列出的权限,因此必须在 android/app/src/main/AndroidManifest.xml
文件中添加以下权限:
<manifest>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application>
...
</application>
</manifest>
开始监听传入的SMS
在添加了 RECEIVE_SMS
权限并请求了SMS权限后,可以使用 listenIncomingSms
函数开始监听传入的SMS:
final easySmsReceiver = EasySmsReceiver.instance;
easySmsReceiver.listenIncomingSms(
onNewMessage: (message) {
// 处理新消息
},
);
在后台监听传入的SMS
可以使用 flutter_background_service
插件在后台监听传入的SMS,如下所示:
import 'package:flutter/material.dart';
import 'package:easy_sms_receiver/easy_sms_receiver.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
// 初始化背景服务的函数
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
iosConfiguration: IosConfiguration(),
androidConfiguration: AndroidConfiguration(
onStart: onStart,
isForegroundMode: true,
autoStart: true,
),
);
}
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
final plugin = EasySmsReceiver.instance;
plugin.listenIncomingSms(
onNewMessage: (message) {
print("You have new message:");
print("::::::Message Address: ${message.address}");
print("::::::Message body: ${message.body}");
// 处理新消息
// 例如:显示通知
if (service is AndroidServiceInstance) {
service.setForegroundNotificationInfo(
title: message.address ?? "address",
content: message.body ?? "body",
);
}
},
);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 请求SMS权限,然后初始化背景服务
Permission.sms.request().then((status) {
if (status.isGranted) initializeService();
});
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Plugin example app')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Latest Received SMS: $_message"),
Text('EasySmsReceiver Status: $_easySmsReceiverStatus\n'),
TextButton(
onPressed: startSmsReceiver, child: Text("Start Receiver")),
TextButton(
onPressed: stopSmsReceiver, child: Text("Stop Receiver")),
],
),
),
),
);
}
}
class _MyAppState extends State<MyApp> {
final EasySmsReceiver easySmsReceiver = EasySmsReceiver.instance;
String _easySmsReceiverStatus = "Undefined";
String _message = "";
@override
void initState() {
super.initState();
}
Future<bool> requestSmsPermission() async {
return await Permission.sms.request().then(
(PermissionStatus pStatus) {
if (pStatus.isPermanentlyDenied) {
// "You must allow sms permission"
openAppSettings();
}
return pStatus.isGranted;
},
);
}
Future<void> startSmsReceiver() async {
// 平台消息可能会失败,因此我们使用 try/catch PlatformException
if (await requestSmsPermission()) {
easySmsReceiver.listenIncomingSms(
onNewMessage: (message) {
print("You have new message:");
print("::::::Message Address: ${message.address}");
print("::::::Message body: ${message.body}");
if (!mounted) return;
setState(() {
_message = message.body ?? "Error reading message body.";
});
},
);
if (!mounted) return;
setState(() {
_easySmsReceiverStatus = "Running";
});
}
}
void stopSmsReceiver() {
easySmsReceiver.stopListenIncomingSms();
if (!mounted) return;
setState(() {
_easySmsReceiverStatus = "Stopped";
});
}
@override
Widget build(BuildContext context) {
return const MyApp();
}
}
停止监听传入的SMS
可以通过调用 stopListenIncomingSms
函数停止监听传入的SMS:
easySmsReceiver.stopListenIncomingSms();
示例代码
以下是完整的示例代码,展示了如何使用 easy_sms_receiver
插件来监听和处理传入的SMS:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:easy_sms_receiver/easy_sms_receiver.dart';
import 'package:permission_handler/permission_handler.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final EasySmsReceiver easySmsReceiver = EasySmsReceiver.instance;
String _easySmsReceiverStatus = "Undefined";
String _message = "";
@override
void initState() {
super.initState();
}
Future<bool> requestSmsPermission() async {
return await Permission.sms.request().then(
(PermissionStatus pStatus) {
if (pStatus.isPermanentlyDenied) {
// "You must allow sms permission"
openAppSettings();
}
return pStatus.isGranted;
},
);
}
Future<void> startSmsReceiver() async {
// 平台消息可能会失败,因此我们使用 try/catch PlatformException
if (await requestSmsPermission()) {
easySmsReceiver.listenIncomingSms(
onNewMessage: (message) {
print("You have new message:");
print("::::::Message Address: ${message.address}");
print("::::::Message body: ${message.body}");
if (!mounted) return;
setState(() {
_message = message.body ?? "Error reading message body.";
});
},
);
if (!mounted) return;
setState(() {
_easySmsReceiverStatus = "Running";
});
}
}
void stopSmsReceiver() {
easySmsReceiver.stopListenIncomingSms();
if (!mounted) return;
setState(() {
_easySmsReceiverStatus = "Stopped";
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Plugin example app')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Latest Received SMS: $_message"),
Text('EasySmsReceiver Status: $_easySmsReceiverStatus\n'),
TextButton(
onPressed: startSmsReceiver, child: Text("Start Receiver")),
TextButton(
onPressed: stopSmsReceiver, child: Text("Stop Receiver")),
],
),
),
),
);
}
}
希望这些信息对你有所帮助!如果你有任何问题或需要进一步的帮助,请随时提问。
更多关于Flutter短信接收插件easy_sms_receiver的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html