Flutter蓝牙连接管理插件watch_ble_connection的使用
Flutter蓝牙连接管理插件watch_ble_connection的使用
安装
Android
- 在应用级别的
build.gradle
文件中添加以下依赖:implementation 'com.google.android.gms:play-services-wearable:17.0.0'
- 确保你的Wear OS应用的
applicationId
与手机应用的applicationId
相同。
iOS
-
确保iOS的部署目标至少为9.3。
-
在你的应用中启用位码以支持。你可以通过以下步骤启用Apple Watch支持:
just follow these instructions to enable apple watch for your app
如何使用
要了解如何在可穿戴设备上访问发送的数据,请查看示例项目。
建议不要依赖于iOS上的即时数据传输,因为 applicationContext
会在低强度情况下才设置这个值。
发送消息
使用静态方法 WatchConnection.sendMessage(Map<String, dynamic> message);
发送单次消息。
- 在Android中,所有消息的路径都将使用
/MessageChannel
。
示例发送消息
WatchConnection.sendMessage({
"text": "Some text",
"integerValue": 1
});
接收消息
使用静态方法 WatchConnection.listenForMessage;
注册一个消息监听器函数。
- (Android特定) 如果消息数据是字符串,则库会假设它是JSON并尝试转换它。如果该操作失败,消息数据将原样发送给监听器。
接收消息示例
// msg 是 Map<String, dynamic> 或字符串(在使用库时务必检查)
WatchListener.listenForMessage((msg) {
print(msg);
});
设置数据项 (datalayer/userConfig)
使用静态方法 WatchConnection.setData(String path, Map<String, dynamic> message);
设置具有指定路径的数据项(使用wearOS兼容的数据层路径)。
- (iOS特定) 路径变量用作应用程序上下文字典中的键。
- (iOS特定) 数据传输不是即时的,并且会在低强度时刻等待。只使用此功能来设置永久性低优先级信息。
示例设置数据
WatchConnection.setData("/actor/cage",{
"name": "Nicolas Saputra",
"awesomeRating": 100
});
监听数据事件
使用静态方法 WatchConnection.listenForDataLayer;
注册一个数据监听器函数。
- (Android特定) 如果数据是字符串,则库会假设它是JSON并尝试转换它。如果该操作失败,数据将原样发送给监听器。
示例监听数据
// data 应该是 Map<String, dynamic>,但在某些情况下也可以是字符串
WatchListener.listenForDataLayer((data) {
print(data);
});
注意事项
- 目前不支持Android上的嵌套数据结构。因此,建议将复杂项目作为JSON字符串发送并在接收端解析。
- 支持的通信类型包括:
- 字符串
- 整数
- 浮点数
- 双精度
- 长整型
- 布尔值
- 单一类型的字符串、浮点数、整数或长整型列表
作者
示例代码
import 'package:flutter/material.dart';
import 'package:watch_ble_connection/watch_ble_connection.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
TextEditingController _controller;
String value = '';
[@override](/user/override)
void initState() {
super.initState();
_controller = TextEditingController();
WatchListener.listenForMessage((msg) {
print(msg);
});
WatchListener.listenForDataLayer((msg) {
print(msg);
});
}
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的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙连接管理插件watch_ble_connection的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用Flutter蓝牙连接管理插件watch_ble_connection
的代码示例。这个示例将展示如何初始化插件、扫描蓝牙设备、连接到特定的蓝牙设备,并进行一些基本的读写操作。
首先,确保你已经在pubspec.yaml
文件中添加了watch_ble_connection
依赖:
dependencies:
flutter:
sdk: flutter
watch_ble_connection: ^最新版本号 # 请替换为实际最新版本号
然后运行flutter pub get
来安装依赖。
初始化插件并扫描设备
import 'package:flutter/material.dart';
import 'package:watch_ble_connection/watch_ble_connection.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late WatchBleConnection _ble;
List<BleDevice> _devices = [];
@override
void initState() {
super.initState();
_ble = WatchBleConnection();
_ble.startScan().then((devices) {
setState(() {
_devices = devices;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Bluetooth Scanner'),
),
body: ListView.builder(
itemCount: _devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_devices[index].name),
onTap: () {
_ble.connectToDevice(_devices[index].id).then((connection) {
// 连接成功后可以进行读写操作
_readData(connection);
// 示例:写入数据(需要设备支持的服务和特性)
// _writeData(connection, someData);
});
},
);
},
),
),
);
}
void _readData(BleConnection connection) {
connection.readCharacteristic(
serviceUuid: '0000180d-0000-1000-8000-00805f9b34fb', // 示例服务UUID
characteristicUuid: '00002a37-0000-1000-8000-00805f9b34fb', // 示例特性UUID
).then((data) {
print('Read data: ${data.toString()}');
}).catchError((error) {
print('Error reading data: $error');
});
}
void _writeData(BleConnection connection, List<int> data) {
connection.writeCharacteristic(
serviceUuid: '0000180d-0000-1000-8000-00805f9b34fb', // 示例服务UUID
characteristicUuid: '00002a37-0000-1000-8000-00805f9b34fb', // 示例特性UUID
value: data,
).then((_) {
print('Data written successfully');
}).catchError((error) {
print('Error writing data: $error');
});
}
}
注意事项
-
权限:确保在Android和iOS的
AndroidManifest.xml
和Info.plist
文件中添加了必要的蓝牙权限。 -
服务UUID和特性UUID:示例中的UUID是通用的电池服务(Battery Service)和电池级别特性(Battery Level Characteristic)。你需要替换为实际设备的服务和特性UUID。
-
错误处理:代码示例中包含了基本的错误处理,但在实际应用中,你可能需要更详细的错误处理和用户反馈。
-
设备管理:当应用进入后台或设备断开连接时,你可能需要处理这些场景,比如重新连接或通知用户。
-
依赖版本:确保使用的是
watch_ble_connection
的最新稳定版本,以避免已知的bug和兼容性问题。
这个示例提供了一个基本的框架,你可以根据实际需求进行扩展和修改。