场景说明
蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的连接。本示例通过@ohos.bluetoothManager接口实现蓝牙设备发现、配对、取消配对功能。
效果呈现
本示例最终效果如下:
运行环境
本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。
- IDE:DevEco Studio 3.1.1 Release
- SDK:Ohos_sdk_full 4.0.8.5(API Version10 Beta1)
实现思路
本文涉及到蓝牙的设备发现、配对、取消配对三个功能特性,实现思路如下:
- 启动和关闭蓝牙:在Index页面中通过Toggle组件的onChange函数控制蓝牙的开关,开关打开的情况下执行initBluetooth函数,关闭的情况下执行bluetooth.disableBluetooth()方法来断开蓝牙;
- 验证蓝牙是否处于连接状态:蓝牙打开的时候通过bluetooth.on(‘stateChange’)方法监听蓝牙连接状态改变事件,如确认已打开,执行foundDevices()函数来查找设备接口,确认已关闭则执行bluetooth.stopBluetoothDiscovery()方法停止查询接口。
- 发现设备:在foundDevices()函数中通过bluetooth.on(‘bluetoothDeviceFind’)方法监听设备发现事件,通过bluetooth.getPairedDevices()方法更新已配对蓝牙地址,然后通过bluetooth.startBluetoothDiscovery()方法开启蓝牙扫描发现远端设备,并且通过bluetooth.setBluetoothScanMode()方法来被远端设备发现。
- 蓝牙配对:通过bluetooth.on(‘pinRequired’)方法监听远端蓝牙设备的配对请求事件,点击配对执行bluetooth.setDevicePairingConfirmation(this.data.deviceId,true)方法,点击取消执行bluetooth.setDevicePairingConfirmation(this.data.deviceId,false)方法。
- 取消配对:使用bluetooth.cancelPairedDevice()断开指定的远端设备连接。
开发步骤
1.申请蓝牙权限。 使用蓝牙需要先申请对应的权限,在module.json5文件中添加以下配置:
"requestPermissions": [
{
//允许应用查看蓝牙的配置
"name": "ohos.permission.USE_BLUETOOTH",
"reason": "$string:grant_use_bluetooth",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "inuse"
}
},
{
//允许应用配置本地蓝牙,查找远端设备且与之配对连接
"name": "ohos.permission.DISCOVER_BLUETOOTH",
"reason": "$string:grant_discovery_bluetooth",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "inuse"
}
},
{
//允许应用获取设备位置信息
"name": "ohos.permission.LOCATION",
"reason": "$string:grant_location",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "inuse"
}
},
{
//允许应用获取设备模糊位置信息
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:grant_location",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "inuse"
}
},
{
//允许应用配对蓝牙设备,并对设备的电话簿或消息进行访问
"name": "ohos.permission.MANAGE_BLUETOOTH",
"reason": "$string:grant_manage_bluetooth",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "inuse"
}
}
]
2.构建UI框架,整体的UI框架分为TitleBar(页面名称),PinDialog(配对蓝牙弹框),index(主页面)三个部分。
//Common/TitleBar.ets
@Component
export struct TitleBar {
private handlerClickButton: () => void
build() {
Row() {
Image($r('app.media.ic_back'))
.width(40)
.height(30)
.onClick(() => {
this.handlerClickButton()
})
Text($r('app.string.bluetooth'))
.fontSize(30)
.width(150)
.height(50)
.margin({
left: 15 })
.fontColor('#ffa2a3a4')
}
.width('100%')
.height(60)
.padding({
left: 20, top: 10 })
.backgroundColor('#ff2d30cb')
.constraintSize(