Flutter蓝牙连接管理插件watch_ble_connection_plugin的使用

Flutter蓝牙连接管理插件watch_ble_connection_plugin的使用

安装

Android
  • 在应用级别的 build.gradle 文件中添加以下依赖:
    implementation 'com.google.android.gms:play-services-wearable:17.0.0'
    
  • 确保 Wear OS 应用的 applicationId 与手机应用的 applicationId 相同。
iOS
  • iOS 的部署目标必须至少为 14.0(适用于向 Apple Watch 发送表盘)。
  • 启用应用的 bitcode 以支持。具体操作可参照这些说明来启用应用的 Apple Watch 支持。

如何使用

  • 若要了解如何在可穿戴设备上访问发送的数据,请查看示例项目。
  • 建议不要依赖于 iOS 上的即时数据传输,因为 applicationContext 会在低强度情况下才会更新应用和手表之间的值。
发送表盘
  • 使用静态方法 WatchConnection.sendWatchface(String path); 发送单个表盘到 Apple Watch。
  • 目前仅支持 iOS 平台上的 Apple Watch。
// 发送表盘文件路径
WatchConnection.sendWatchface("/var/.../Portrait.watchface");
发送消息
  • 使用静态方法 WatchConnection.sendMessage(Map<String, dynamic> message); 发送单次消息。
  • 在 Android 上,所有消息将使用路径 /MessageChannel
// 发送消息
WatchConnection.sendMessage({
  "text": "Some text",
  "integerValue": 1
});
接收消息
  • 使用静态方法 WatchConnection.listenForMessage; 注册一个消息监听器函数。
  • 如果消息数据是字符串,则库会尝试将其转换为 JSON。如果该操作失败,消息数据将原样发送给监听器。
// 注册消息监听器
WatchListener.listenForMessage((msg) {
  print(msg);
});
设置数据项
  • 使用静态方法 WatchConnection.setData(String path, Map<String, dynamic> message); 设置指定路径的数据项(使用 Wear OS 兼容的数据层路径)。
  • 在 iOS 中,路径变量将作为应用程序上下文字典中的键。
  • 数据传输不是即时的,而是在低强度时刻进行。仅用于设置低优先级信息。
// 设置数据
WatchConnection.setData("/actor/cage",{
    "name": "Nicolas Saputra",
    "awesomeRating": 100
});
监听数据事件
  • 使用静态方法 WatchConnection.listenForDataLayer; 注册一个数据监听器函数。
  • 如果数据是字符串,则库会尝试将其转换为 JSON。如果该操作失败,数据将原样发送给监听器。
// 监听数据
WatchListener.listenForDataLayer((data) {
  print(data);
});

注意事项

  • 目前在 Android 上不支持嵌套数据结构。因此建议将复杂项目作为 JSON 字符串发送并在接收端解析。
  • 支持的通信类型包括:
    • 字符串
    • 整数
    • 浮点数
    • 双精度浮点数
    • 长整型
    • 布尔值
    • 单一类型的列表(字符串、浮点数、整数或长整型)

示例代码

import 'package:flutter/material.dart';
import 'package:watch_ble_connection_plugin/watch_ble_connection_plugin.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late TextEditingController _controller;
  String value = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    _controller = TextEditingController();

    // 注册消息监听器
    WatchListener.listenForMessage((msg) {
      print(msg);
    });

    // 注册数据监听器
    WatchListener.listenForDataLayer((msg) {
      print(msg);
    });
  }

  [@override](/user/override)
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Example app'),
        ),
        body: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextField(
                  controller: _controller,
                  decoration: InputDecoration(border: InputBorder.none, labelText: 'Enter some text'),
                  onChanged: (String val) async {
                    setState(() {
                      value = val;
                    });
                  },
                ),
                OutlinedButton(
                  child: Text('Send message to Watch'),
                  onPressed: () {
                    primaryFocus?.unfocus(disposition: UnfocusDisposition.scope);
                    WatchConnection.sendMessage({"text": value});
                  },
                ),
                OutlinedButton(
                  child: Text('Set data on Watch'),
                  onPressed: () {
                    primaryFocus?.unfocus(disposition: UnfocusDisposition.scope);
                    WatchConnection.setData("message", {
                      "text": value != "" ? value : "test", // 确保我们至少有空字符串
                      "integerValue": 1,
                      "intList": [1, 2, 3],
                      "stringList": ["one", "two", "three"],
                      "floatList": [1.0, 2.4, 3.6],
                      "longList": []
                    });
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter蓝牙连接管理插件watch_ble_connection_plugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙连接管理插件watch_ble_connection_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


watch_ble_connection_plugin 是一个用于管理 Flutter 应用与蓝牙设备连接的插件。它可以帮助你轻松地连接、断开连接、发送和接收数据等操作。以下是如何使用 watch_ble_connection_plugin 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 watch_ble_connection_plugin 的依赖:

dependencies:
  flutter:
    sdk: flutter
  watch_ble_connection_plugin: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入插件:

import 'package:watch_ble_connection_plugin/watch_ble_connection_plugin.dart';

3. 初始化插件

在使用插件之前,通常需要先初始化它:

void initBlePlugin() async {
  await WatchBleConnectionPlugin.initialize();
}

4. 扫描蓝牙设备

你可以使用插件提供的功能来扫描附近的蓝牙设备:

void scanDevices() async {
  List<BluetoothDevice> devices = await WatchBleConnectionPlugin.scanDevices();
  devices.forEach((device) {
    print('Device found: ${device.name}, ${device.id}');
  });
}

5. 连接蓝牙设备

扫描到设备后,你可以选择连接某个设备:

void connectToDevice(String deviceId) async {
  bool isConnected = await WatchBleConnectionPlugin.connect(deviceId);
  if (isConnected) {
    print('Connected to device: $deviceId');
  } else {
    print('Failed to connect to device: $deviceId');
  }
}

6. 断开连接

当你不再需要连接时,可以断开连接:

void disconnectDevice(String deviceId) async {
  bool isDisconnected = await WatchBleConnectionPlugin.disconnect(deviceId);
  if (isDisconnected) {
    print('Disconnected from device: $deviceId');
  } else {
    print('Failed to disconnect from device: $deviceId');
  }
}

7. 发送和接收数据

连接成功后,你可以通过蓝牙发送和接收数据:

void sendData(String deviceId, List<int> data) async {
  await WatchBleConnectionPlugin.sendData(deviceId, data);
}

void listenForData(String deviceId) {
  WatchBleConnectionPlugin.listenForData(deviceId).listen((data) {
    print('Received data: $data');
  });
}

8. 处理连接状态

你可以监听蓝牙连接状态的变化:

void listenForConnectionStatus(String deviceId) {
  WatchBleConnectionPlugin.listenForConnectionStatus(deviceId).listen((status) {
    print('Connection status: $status');
  });
}

9. 错误处理

在使用插件时,建议处理可能出现的错误:

void connectToDevice(String deviceId) async {
  try {
    bool isConnected = await WatchBleConnectionPlugin.connect(deviceId);
    if (isConnected) {
      print('Connected to device: $deviceId');
    } else {
      print('Failed to connect to device: $deviceId');
    }
  } catch (e) {
    print('Error connecting to device: $e');
  }
}

10. 清理资源

在应用退出或不再需要蓝牙连接时,记得清理资源:

void dispose() {
  WatchBleConnectionPlugin.dispose();
}
回到顶部