鸿蒙HarmonyOS SDK
设备发现
蓝牙发现

蓝牙发现

蓝牙发现由 GizBluetoothManager 提供。开始前应完成核心与蓝牙模块初始化,并通过 HarmonyOS 原生权限 API 取得用户授权。

监听发现结果

subscribeBluetoothDeviceList() 返回 GizState<Array<GizDevice>>。先订阅再扫描,避免漏掉首批结果。

import { GizDevice } from '@gizwits/smart-sdk';
import { GizBluetoothManager } from '@gizwits/smart-sdk-bluetooth';
 
let bluetoothDevices: Array<GizDevice> = [];
const unsubscribeBluetooth = GizBluetoothManager
  .subscribeBluetoothDeviceList()
  .subscribe((devices: Array<GizDevice>): void => {
    bluetoothDevices = devices;
  });

开始扫描

GizBluetoothManager.startBleScan();

重复调用不会并发启动多个扫描。结果只包含 ProductKey 与核心配置匹配的设备。

查询扫描状态

const scanning: boolean = GizBluetoothManager.isScanning();

停止扫描

GizBluetoothManager.stopBleScan();
unsubscribeBluetooth();

页面离开或不再需要附近设备时,应同时停止系统扫描并取消订阅。

读取广播与底层会话

const advertisement = GizBluetoothManager.getAdvertisement(device.id);
const session = GizBluetoothManager.getSession(device.id);

这两个接口用于高级诊断。普通业务应通过 device.bleCapability 操作设备,以保持状态和自动重连逻辑一致。

扫描无结果时检查 ProductKey、系统蓝牙、动态权限、设备广播状态和设备距离。