Flutter短信接收插件easy_sms_receiver的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter短信接收插件easy_sms_receiver的使用

easy_sms_receiver

pub package

easy_sms_receiver 是一个Flutter插件,用于在Android平台上监听和读取传入的SMS。

使用方法

要在项目中使用此插件,需要在 pubspec.yaml 文件中添加 easy_sms_receiver 作为依赖项。

dependencies:
  easy_sms_receiver: ^0.0.1

此外,还需要添加 permission_handlerflutter_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

1 回复

更多关于Flutter短信接收插件easy_sms_receiver的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用easy_sms_receiver插件的详细步骤,包括相关代码案例。

步骤 1: 添加依赖

首先,在你的Flutter项目的pubspec.yaml文件中添加easy_sms_receiver依赖:

dependencies:
  flutter:
    sdk: flutter
  easy_sms_receiver: ^最新版本号  # 请替换为实际最新版本号

然后运行flutter pub get来获取依赖。

步骤 2: 配置Android权限

android/app/src/main/AndroidManifest.xml文件中添加必要的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>

    <application
        ...>
        
        <!-- 添加广播接收器 -->
        <receiver android:name="com.github.zhangchi04.easysmsreceiver.SmsBroadcastReceiver"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
        
    </application>
</manifest>

步骤 3: 请求权限

在Dart代码中请求必要的运行时权限。你可以在MainActivity.kt(对于Kotlin)或MainActivity.java(对于Java)中请求权限,或者通过Flutter插件如permission_handler。这里我们使用permission_handler

pubspec.yaml中添加permission_handler依赖:

dependencies:
  flutter:
    sdk: flutter
  easy_sms_receiver: ^最新版本号
  permission_handler: ^最新版本号  # 请替换为实际最新版本号

然后在你的Dart代码中请求权限:

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:easy_sms_receiver/easy_sms_receiver.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('SMS Receiver Demo'),
        ),
        body: SmsReceiverScreen(),
      ),
    );
  }
}

class SmsReceiverScreen extends StatefulWidget {
  @override
  _SmsReceiverScreenState createState() => _SmsReceiverScreenState();
}

class _SmsReceiverScreenState extends State<SmsReceiverScreen> {
  String _smsMessage = "";

  @override
  void initState() {
    super.initState();
    _requestPermissions();
    EasySmsReceiver.addSmsListener((message) {
      setState(() {
        _smsMessage = message;
      });
    });
  }

  void _requestPermissions() async {
    Map<Permission, PermissionStatus> statuses = await Permission.getPermissionsStatus([
      Permission.sms,
      Permission.receiveSms,
    ]);

    if (statuses[Permission.sms] != PermissionStatus.granted ||
        statuses[Permission.receiveSms] != PermissionStatus.granted) {
      Map<Permission, PermissionResult> results = await Permission.requestPermissions([
        Permission.sms,
        Permission.receiveSms,
      ]);

      if (results[Permission.sms] == PermissionResult.granted &&
          results[Permission.receiveSms] == PermissionResult.granted) {
        print("Permissions granted");
      } else {
        print("Permissions denied");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Last Received SMS:"),
          Text(_smsMessage),
        ],
      ),
    );
  }
}

步骤 4: 运行应用

确保你已经正确配置并请求了权限,然后运行你的Flutter应用。当接收到新的SMS时,你应该能够在应用的界面上看到接收到的短信内容。

注意事项

  1. 测试环境:在实际设备上进行测试,因为模拟器可能不支持接收SMS。
  2. 权限处理:确保用户已经授予了必要的权限,否则插件将无法正常工作。
  3. 隐私政策:由于短信内容属于敏感信息,确保你的应用有明确的隐私政策,并且用户同意处理他们的短信数据。

这样,你就完成了在Flutter中使用easy_sms_receiver插件来接收短信的功能。

回到顶部