flutter实现自动连接蓝牙

不会flutter可以做蓝牙吗

我的回答是可以的,0基础flutter半天时间搞定蓝牙功能,首先介绍一款github上的插件 flutter_blue_elves 源码简单易懂基本都是中文注释
github地址 https://github.com/pineappleoOilPrince/flutter_blue_elves

使用方式

使用方式与一般的flutter插件一样,引用依赖后在要用的地方导包即可

import 'package:flutter_blue_elves/flutter_blue_elves.dart';

蓝牙权限

安装完后开始正式使用,首先使用蓝牙时需要打开GPS以及蓝牙功能,这里插件给了定位的权限以及蓝牙权限,定位功能以及蓝牙功能的使用

  FlutterBlueElves.instance.androidCheckBlueLackWhat().then((values) {
    if (values.toString() == '[]') {
      concact();   // 这里判断是否连接上蓝牙
    } else {
      if (values.contains(AndroidBluetoothLack.bluetoothPermission)) {
        print("没有授予蓝牙权限");
        FlutterBlueElves.instance.androidApplyBluetoothPermission((isOk) {
          print(isOk ? "用户同意开启蓝牙权限" : "用户不同意开启蓝牙权限");
        });
      }
      if (values.contains(AndroidBluetoothLack.locationPermission)) {
        print("没有授予定位权限");
        FlutterBlueElves.instance.androidApplyLocationPermission((isOk) {
          print(isOk ? "用户同意授予位置权限" : "用户不同意授予位置权限");
        });
      }
      if (values.contains(AndroidBluetoothLack.locationFunction)) {
        print("没有开启定位功能");
        FlutterBlueElves.instance.androidOpenLocationService((isOk) {
          print(isOk ? "用户同意开启定位功能" : "用户不同意开启定位功能");
        });
      }
      if (values.contains(AndroidBluetoothLack.bluetoothFunction)) {
        print("没有开启蓝牙功能");
        FlutterBlueElves.instance.androidOpenBluetoothService((isOk) {
          if (isOk) {
            print('开启蓝牙了');
            concact();
          }
        });
      }
    }
  });

如果没有开启定位以及蓝牙功能都会自动弹出界面

蓝牙自动连接读取数据

权限都开启后,蓝牙开始扫描 startScan 为开始扫描的时间 数字为时间
扫描到的ScanItem 看一下数据类型 这里我们所要的是ID以及RSSI以及name

class ScanResult {
  ///设备Id
  late final String _id;

  ///设备名称
  late final String? _name;

  ///设备localName
  late final String? _localName;

  ///mac地址,ios没有返回
  late final String? _macAddress;

  ///蓝牙信号强度
  late final int _rssi;

  ///设备uuid
  late final List _uuids;

  ///厂商自定义数据
  late final Map? _manufacturerSpecificData;

  ///原始广播包数据
  late final Uint8List? _row;

  ScanResult._(this._id, this._name, this._localName, this._macAddress,
      this._rssi, this._uuids, this._manufacturerSpecificData, this._row);

  Uint8List? get row => _row;

  String? get localName => _localName;

  Map? get manufacturerSpecificData => _manufacturerSpecificData;

  List get uuids => _uuids;

  int get rssi => _rssi;

  String? get macAddress => _macAddress;

  String? get name => _name;

  String get id => _id;

这边是通过vue传过来的Global.UUID,匹配到相同的ID开始连接,连接后通过stateStream.listen监听到连接的状态,连接成功后停止扫描,通过serviceDiscoveryStream.listen事件监听到serviceUuid,通过vue传过来的接收数据的服务ID以及特征值,来判断接收的服务ID以及特征值。这样就可以实现自动连接以及监听蓝牙的数据。

//    startcan
  FlutterBlueElves.instance.startScan(100000).listen((scanItem) {
    eventBus.fire(MYStaus('连接中'));
    print(scanItem.id);     // scanItem
    if (Global.UUID == scanItem.id) {
      Device device = scanItem.connect(connectTimeout: 100000);
      device.stateStream.listen((newState) {
        // 状态
        if (newState == DeviceState.disconnected) {
          eventBus.fire(MYStaus('连接失败'));
          device.destroy();
          concact();
        } else if (newState == DeviceState.connectTimeout) {
          eventBus.fire(MYStaus('连接超时'));
          device.destroy();
          concact();
        } else if (newState == DeviceState.connected) {
          FlutterBlueElves.instance.stopScan();
          device.serviceDiscoveryStream.listen((serviceItem) {
            if (serviceItem.serviceUuid == Global.SERVERID) {
              device.setNotify(serviceItem.serviceUuid, Global.CHARTIDS, true);
            }
          });
          device.discoveryService();
          device.deviceSignalResultStream.listen((result) {
            eventBus.fire(MYStaus('已连接'));
            eventBus.fire(ScanEvent(result.data.toString()));
          });
        } else if (newState == DeviceState.initiativeDisConnected) {
          print('------------------手动');
        } else {
          print('断开连接了');
        }
      }).onDone(() {
        eventBus.fire(MYStaus('连接发生错误'));
        device.destroy();
        blequanxian();
      });
    } else {
      eventBus.fire(MYStaus('扫描匹配设备中'));
      var _counter = 0;
      Timer timer = Timer.periodic(const Duration(seconds: 60), (timer) {
        _counter++;
        blequanxian();
        if (_counter == 5) {
          timer.cancel();
          print("执行5次之后停止定时器");
        }
      });
    }
  });
好的,以下是一个简单的蓝牙控制页面的 Flutter 代码,使用了 `flutter_bluetooth_serial` 插件: ```dart import 'package:flutter/material.dart'; import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart'; class BluetoothControlPage extends StatefulWidget { @override _BluetoothControlPageState createState() => _BluetoothControlPageState(); } class _BluetoothControlPageState extends State<BluetoothControlPage> { // 蓝牙实例 FlutterBluetoothSerial _bluetooth = FlutterBluetoothSerial.instance; // 是否正在搜索设备 bool _isDiscovering = false; // 当前连接的设备 BluetoothDevice _device; // 蓝牙设备列表 List<BluetoothDevice> _devicesList = []; // 初始化蓝牙 void _initBluetooth() async { // 检查蓝牙是否可用 bool isEnabled = await _bluetooth.isEnabled; if (!isEnabled) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("蓝牙未开启"), content: Text("请先开启蓝牙"), actions: [ FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("确定"), ), ], ); }, ); } } // 开始搜索设备 void _startDiscovery() { setState(() { _isDiscovering = true; }); _bluetooth.startDiscovery().listen((device) { setState(() { _devicesList.add(device); }); }).onDone(() { setState(() { _isDiscovering = false; }); }); } // 连接设备 void _connectToDevice(BluetoothDevice device) async { try { await _bluetooth.cancelDiscovery(); await device.connect(); setState(() { _device = device; }); } catch (e) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("连接失败"), content: Text("请确认设备是否可用"), actions: [ FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("确定"), ), ], ); }, ); } } // 发送数据 void _sendData(String data) async { try { await _device.write(data); } catch (e) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("发送失败"), content: Text("请确认设备是否连接"), actions: [ FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("确定"), ), ], ); }, ); } } @override void initState() { super.initState(); _initBluetooth(); } @override void dispose() { _bluetooth.cancelDiscovery(); _device.disconnect(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("蓝牙控制页面"), ), body: Container( padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("蓝牙设备列表:"), Expanded( child: ListView.builder( itemCount: _devicesList.length, itemBuilder: (BuildContext context, int index) { BluetoothDevice device = _devicesList[index]; return ListTile( title: Text(device.name), subtitle: Text(device.address), onTap: () { _connectToDevice(device); }, ); }, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ _isDiscovering ? CircularProgressIndicator() : RaisedButton( child: Text("搜索设备"), onPressed: () { _startDiscovery(); }, ), RaisedButton( child: Text("发送数据"), onPressed: () { _sendData("Hello, Bluetooth!"); }, ), ], ), ], ), ), ); } } ``` 这里是一个简单的蓝牙控制页面,包括检查权限、搜索设备、连接设备、发送数据等基本功能。需要注意的是,由于 `flutter_bluetooth_serial` 插件目前不支持 BLE 模式,因此只能检索到经典模式的蓝牙设备。如果需要支持 BLE 模式,可以考虑使用其他插件,如 `flutter_blue`。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oomsday

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值