Files
tuiche/lib/common/util/BluetoothHelper.dart
2025-09-01 10:51:01 +08:00

52 lines
1.6 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
class BluetoothHelper {
static StreamSubscription<BluetoothAdapterState>? _subscription;
/// 获取当前蓝牙是否开启(跨平台封装)
// static Future<bool> isBluetoothOn({Duration timeout = const Duration(seconds: 2)}) async {
// // 先尝试直接获取Android 上几乎即时可用)
// bool directCheck = await FlutterBluePlus.isOn;
// if (directCheck) return true;
// // iOS 上有初始化延迟,用 adapterState.first 再确认一次
// try {
// BluetoothAdapterState state = await FlutterBluePlus.adapterState
// .firstWhere((s) => s != BluetoothAdapterState.unknown,
// orElse: () => BluetoothAdapterState.unknown)
// .timeout(timeout);
// return state == BluetoothAdapterState.on;
// } catch (_) {
// return false;
// }
// }
static Future<bool> isBluetoothOn(
{Duration timeout = const Duration(seconds: 2)}) async {
try {
BluetoothAdapterState state = await FlutterBluePlus.adapterState
.firstWhere((s) => s != BluetoothAdapterState.unknown)
.timeout(timeout);
return state == BluetoothAdapterState.on;
} catch (_) {
return false;
}
}
/// 监听蓝牙状态变化
static void listenBluetoothState(void Function(bool isOn) onChange) {
_subscription?.cancel();
_subscription = FlutterBluePlus.adapterState.listen((state) {
onChange(state == BluetoothAdapterState.on);
});
}
/// 停止监听
static void cancelListener() {
_subscription?.cancel();
_subscription = null;
}
}