赞
踩
蓝牙是短距离无线通信的一种方式,支持蓝牙的两个设备必须配对后才能通信。HarmonyOS蓝牙主要分为传统蓝牙和低功耗蓝牙(通常称为BLE,Bluetooth Low Energy)。传统蓝牙指的是蓝牙版本3.0以下的蓝牙,低功耗蓝牙指的是蓝牙版本4.0以上的蓝牙。
当前蓝牙的配对方式有两种:蓝牙协议2.0以下支持PIN码(Personal Identification Number,个人识别码)配对,蓝牙协议2.1以上支持简单配对。
HarmonyOS传统蓝牙提供的功能有:
BLE设备交互时会分为不同的角色:
HarmonyOS低功耗蓝牙提供的功能有:
调用蓝牙的打开接口需要ohos.permission.USE_BLUETOOTH权限,调用蓝牙扫描接口需要ohos.permission.LOCATION权限和ohos.permission.DISCOVER_BLUETOOTH权限。
传统蓝牙本机管理主要是针对蓝牙本机的基本操作,包括打开和关闭蓝牙、设置和获取本机蓝牙名称、扫描和取消扫描周边蓝牙设备、获取本机蓝牙profile对其他设备的连接状态、获取本机蓝牙已配对的蓝牙设备列表。
接口名 | 功能描述 |
---|---|
getDefaultHost(Context context) | 获取BluetoothHost实例,去管理本机蓝牙操作。 |
enableBt() | 打开本机蓝牙。 |
disableBt() | 关闭本机蓝牙。 |
setLocalName(String name) | 设置本机蓝牙名称。 |
getLocalName() | 获取本机蓝牙名称。 |
getBtState() | 获取本机蓝牙状态。 |
startBtDiscovery() | 发起蓝牙设备扫描。 |
cancelBtDiscovery() | 取消蓝牙设备扫描。 |
isBtDiscovering() | 检查蓝牙是否在扫描设备中。 |
getProfileConnState(int profile) | 获取本机蓝牙profile对其他设备的连接状态。 |
getPairedDevices() | 获取本机蓝牙已配对的蓝牙设备列。 |
- // 获取蓝牙本机管理对象
- BluetoothHost bluetoothHost = BluetoothHost.getDefaultHost(context);
- // 调用打开接口
- bluetoothHost.enableBt();
- // 调用获取蓝牙开关状态接口
- int state = bluetoothHost.getBtState();
- //开始扫描
- bluetoothHost.startBtDiscovery();
- //接收系统广播
- public class MyCommonEventSubscriber extends CommonEventSubscriber {
- @Override
- public void onReceiveEvent(CommonEventData data) {
- if (data == null) {
- return;
- }
- Intent info = data.getIntent();
- if (info == null) {
- return;
- }
- //获取系统广播的action
- String action = info.getAction();
- //判断是否为扫描到设备的广播
- if (BluetoothRemoteDevice.EVENT_DEVICE_DISCOVERED.equals(action)) {
- IntentParams myParam = info.getParams();
- BluetoothRemoteDevice device = (BluetoothRemoteDevice) myParam.getParam(BluetoothRemoteDevice.REMOTE_DEVICE_PARAM_DEVICE);
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
传统蓝牙远端管理操作主要是针对远端蓝牙设备的基本操作,包括获取远端蓝牙设备地址、类型、名称和配对状态,以及向远端设备发起配对。
接口名 | 功能描述 |
---|---|
getDeviceAddr() | 获取远端蓝牙设备地址。 |
getDeviceClass() | 获取远端蓝牙设备类型。 |
getDeviceName() | 获取远端蓝牙设备名称。 |
getPairState() | 获取远端设备配对状态。 |
startPair() | 向远端设备发起配对。 |
- 调用getDeviceAddr(),获取远端蓝牙设备地址。
- // 获取蓝牙本机管理对象
- BluetoothHost bluetoothHost = BluetoothHost.getDefaultHost(context);
- // 调用打开接口
- bluetoothHost.enableBt();
- // 调用扫描接口
- bluetoothHost.startBtDiscovery();
- // 设置界面会显示出扫描结果列表,点击蓝牙设备去配对
- BluetoothRemoteDevice device = bluetoothHost.getRemoteDev(TEST_ADDRESS);
- device.startPair();
- // 调用接口获取远端蓝牙设备地址
- String deviceAddr = device.getDeviceAddr();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。