You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查询指定MAC地址的已配对蓝牙设备连接状态(无需扫描)

检查特定蓝牙设备的连接状态(无需扫描)

针对你的需求,无需扫描即可检查特定MAC/UUID设备的连接状态,并监听状态变化,以下是基于Flutter的具体实现方案,分第三方库和原生插件两种路径:

一、使用第三方库(推荐:flutter_blue_plus)

flutter_blue_plus 提供了直接获取已连接设备列表的API,无需先执行扫描操作,完全符合你的需求:

1. 检查设备是否已连接

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

/// 检查目标MAC地址的设备是否已连接(Android)
/// iOS请替换为设备UUID(因iOS隐私限制无法直接使用MAC)
Future<bool> checkTargetDeviceConnection(String targetId) async {
  // 获取当前所有已连接的蓝牙设备
  List<BluetoothDevice> connectedDevices = await FlutterBluePlus.instance.connectedDevices;
  // 匹配目标设备ID
  return connectedDevices.any((device) => device.remoteId.str == targetId);
}

2. 监听连接状态变化

可以直接监听目标设备的状态流,实时同步UI:

void setupConnectionListener(String targetId) async {
  List<BluetoothDevice> connectedDevices = await FlutterBluePlus.instance.connectedDevices;
  // 查找目标设备
  BluetoothDevice? targetDevice = connectedDevices.firstWhere(
    (device) => device.remoteId.str == targetId,
    orElse: () => null,
  );

  if (targetDevice != null) {
    // 监听该设备的连接状态
    targetDevice.state.listen((state) {
      if (state == BluetoothDeviceState.connected) {
        // 更新UI:设备已连接
      } else if (state == BluetoothDeviceState.disconnected) {
        // 更新UI:设备已断开
      }
    });
  }
}

注意事项

  • Android:需要在AndroidManifest.xml中添加权限:
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <!-- 适配Android 12以下版本 -->
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    
  • iOS:无法通过MAC地址识别设备,需使用设备的UUID;同时在Info.plist中添加蓝牙权限描述:
    <key>NSBluetoothAlwaysUsageDescription</key>
    <string>需要蓝牙权限连接设备</string>
    

二、原生插件实现(自定义逻辑)

如果第三方库无法满足需求,可以通过MethodChannel调用原生API实现:

Android端(Kotlin)

  1. 获取已连接的已配对设备:
fun getConnectedBondedDevices(): List<String> {
    val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    val adapter = bluetoothManager.adapter
    return adapter.bondedDevices
        .filter { it.connectionState == BluetoothDevice.STATE_CONNECTED }
        .map { it.address }
}
  1. 注册广播监听连接状态变化:
private val bluetoothReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val device = intent?.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
        val isConnected = intent.action == BluetoothDevice.ACTION_ACL_CONNECTED
        // 通过MethodChannel发送状态到Flutter
        methodChannel.invokeMethod("onConnectionStateChanged", mapOf(
            "mac" to device.address,
            "connected" to isConnected
        ))
    }
}

// 在Activity/Fragment中注册广播
val filter = IntentFilter().apply {
    addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
    addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
}
registerReceiver(bluetoothReceiver, filter)

iOS端(Swift)

  1. 获取已连接设备:
func getConnectedPeripherals(serviceUUID: String) -> [String] {
    let centralManager = CBCentralManager()
    let uuid = CBUUID(string: serviceUUID)
    return centralManager.retrieveConnectedPeripherals(withServices: [uuid])
        .map { $0.identifier.uuidString }
}
  1. 监听连接状态(通过CBCentralManagerDelegate):
extension YourViewController: CBCentralManagerDelegate {
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        methodChannel.invokeMethod("onConnectionStateChanged", arguments: [
            "uuid": peripheral.identifier.uuidString,
            "connected": true
        ])
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        methodChannel.invokeMethod("onConnectionStateChanged", arguments: [
            "uuid": peripheral.identifier.uuidString,
            "connected": false
        ])
    }
}

总结

  1. 优先使用flutter_blue_plus的connectedDevicesAPI,快速实现需求,无需自定义原生代码
  2. 跨平台开发需注意Android用MAC、iOS用UUID的差异
  3. 确保配置好对应平台的蓝牙权限,避免功能异常

内容的提问来源于stack exchange,提问作者infinitesimal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:30:52