鸿蒙OS开发文档 鸿蒙OS 传统蓝牙本机管理

2024-02-25 开发教程 鸿蒙OS开发文档 匿名 0

场景介绍

传统蓝牙本机管理主要是针对蓝牙本机的基本操作,包括打开和关闭蓝牙、设置和获取本机蓝牙名称、扫描和取消扫描周边蓝牙设备、获取本机蓝牙 profile 对其他设备的连接状态、获取本机蓝牙已配对的蓝牙设备列表。

接口说明

接口名功能描述
getDefaultHost(Context context)获取BluetoothHost实例,去管理本机蓝牙操作。
enableBt()打开本机蓝牙。
disableBt()关闭本机蓝牙。
setLocalName(String name)设置本机蓝牙名称。
getLocalName()获取本机蓝牙名称。
getBtState()获取本机蓝牙状态。
startBtDiscovery()发起蓝牙设备扫描。
cancelBtDiscovery()取消蓝牙设备扫描。
isBtDiscovering()检查蓝牙是否在扫描设备中。
getProfileConnState(int profile)获取本机蓝牙profile对其他设备的连接状态。
getPairedDevices()获取本机蓝牙已配对的蓝牙设备列。

打开蓝牙

  1. 调用 BluetoothHost 的 getDefaultHost(Context context) 接口,获取 BluetoothHost 实例,管理本机蓝牙操作。
  1. 调用 enableBt() 接口,打开蓝牙。
  1. 调用 getBtState(),查询蓝牙是否打开。
// 获取蓝牙本机管理对象
BluetoothHost bluetoothHost = BluetoothHost.getDefaultHost(context);
// 调用打开接口
bluetoothHost.enableBt();
// 调用获取蓝牙开关状态接口
int state = bluetoothHost.getBtState();

蓝牙扫描

  1. 开始蓝牙扫描前要先注册广播 BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED。
  1. 调用 startBtDiscovery() 接口开始进行扫描外围设备。
  1. 如果想要获取扫描到的设备,必须在注册广播时继承实 现CommonEventSubscriber 类的 onReceiveEvent(CommonEventData data) 方法,并接收 EVENT_DEVICE_DISCOVERED 广播。
//开始扫描
mBluetoothHost.startBtDiscovery();
//接收系统广播
public class MyCommonEventSubscriber extends CommonEventSubscriber {
@Override
public void onReceiveEvent(CommonEventData var){
Intent info = var.getIntent();
if(info == null) return;
//获取系统广播的action
String action = info.getAction();
//判断是否为扫描到设备的广播
if(action == BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED){
IntentParams myParam = info.getParams();
BluetoothRemoteDevice device = (BluetoothRemoteDevice)myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
}
}
}