蓝牙连接的问题,HarmonyOS 鸿蒙Next新人求助各位大佬救救我
蓝牙连接的问题,HarmonyOS 鸿蒙Next新人求助各位大佬救救我
在开发鸿蒙APP的过程中,依据参考API9文档,使用bluetoothManager.sppAccept(serverNumber, acceptClientSocket);
接口时候发生错误
在
function serverSocket(code,number){
//监听蓝牙串口通信连接的回调函数或处理程序
//当有数据来临时,会调用本接口处理相关操作
console.log('bluetooth error number is'+code.code)
if(code.code==0){
console.log('bluetooth serverSocket Number'+number)
promptAction.showToast({"message":"servercode"+number})
serverNumber=number
}else {
// promptAction.showToast({"message":"没找到啊啊啊啊啊啊"+code.code+number})
}
}
这个函数中,获取的code.code
为什么为-1,且无法获取到number
的值,打印number
值为undefined。这个页面具体代码如下
// xxx.ets
import Bluetooth from '@system.bluetooth'
import bluetoothManager from '@ohos.bluetoothManager'
import { TitleBar } from '../common/uicard/TitleBar'
import promptAction from '@ohos.promptAction'
@Entry
@Component
struct BluetoothPage {
// 蓝牙开关标识位
@State isOn: boolean = false
//蓝牙开启标识
enable:any=false
//蓝牙关闭标示
diable:any=false
// Spp设备发现列表
@State discoverySppList: Array<string> = []
// Spp配对设备列表
@State deviceSppList: Array<string> = []
// Spp设备名字列表
@State SppInfo:Array<ArrayBuffer> = []
// Spp信号强度列表
@State SppRssi:Array<string> = []
handlerClickButton = () => {
// let context = getContext(this) as any
globalThis.abilityContext.terminateSelf()
}
/**
* 蓝牙逻辑部分
*/
OpenBluetooth(){
// bluetoothManager.enableBluetooth()//开启蓝牙
// this.enable=bluetoothManager.enableBluetooth()//开启蓝牙
// if(this.enable==true){
// promptAction.showToast({
// message:'已开启蓝牙'+this.enable,duration:2000,
// })
// }else {
// promptAction.showToast({
// message:this.enable,duration:2000,
// })
// }
bluetoothManager.setBluetoothScanMode(bluetoothManager.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
let deviceId;
function onReceiveEvent(data) {
deviceId = data;
}
bluetoothManager.on("bluetoothDeviceFind",onReceiveEvent)
}
OffBluetooth(){
bluetoothManager.off('bluetoothDeviceFind')//取消订阅蓝牙设备
bluetoothManager.stopBluetoothDiscovery()//关闭蓝牙扫描
bluetoothManager.disableBluetooth()//关闭蓝牙
this.diable=bluetoothManager.disableBluetooth()
if(this.diable==true){
promptAction.showToast({
message:'已关闭蓝牙'+this.diable,duration:2000,
})
}else {
promptAction.showToast({
message:this.diable,duration:2000,
})
}
}
SetBluetoothListen(){
let serverNumber=-1//存储服务端号码
function serverSocket(code,number){
//监听蓝牙串口通信连接的回调函数或处理程序
//当有数据来临时,会调用本接口处理相关操作
console.log('bluetooth error number is'+code.code)
if(code.code==0){
console.log('bluetooth serverSocket Number'+number)
promptAction.showToast({"message":"servercode"+number})
serverNumber=number
}else {
// promptAction.showToast({"message":"没找到啊啊啊啊啊啊"+code.code+number})
}
}
//spp监听配置参数UUID
let sppOption = {"uuid": '00001810-0000-1000-8000-00805F9B34FB', "secure": false, "type": 0};
//服务名称,spp监听配置参数,表示回调函数的入参,服务端Socket的id
try {
bluetoothManager.sppListen('server1',sppOption,serverSocket)
promptAction.showToast({"message":sppOption+"x"+serverSocket})
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
promptAction.showToast({"message":err.code+"xxx"+err.message})
}
//服务端监听socket等待客户端连接。
let clientNumber=-1;
function acceptClientSocket(code,number){
console.log('bluetooth error code is aaa'+code.code)
if(code.code==0){
console.log('bluetoorh clientSocket Number is'+number)
// 获取的clientNumber用作服务端后续读/写操作socket的id。
clientNumber = number;
}
}
try {
bluetoothManager.sppAccept(serverNumber, acceptClientSocket);
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);//传入参数有误servercode
//\promptAction.showToast({"message":err.code+"xxx"+err.message})
}
}
connectSppBluetooth(){
let clientNumber=-1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: '+ number);
// 获取的clientNumber用作客户端后续读/写操作socket的id。
clientNumber = number;
}
let sppOption = {"uuid": '00001810-0000-1000-8000-00805F9B34FB', "secure": false, "type": 0};
try {
bluetoothManager.sppConnect('E4:65:B8:12:BB:1E', sppOption, clientSocket);
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
promptAction.showToast({"message":err.code+"xxx"+err.message})
}
}
/**
* UI部分
*/
build() {
Column() {
TitleBar({ handlerClickButton: this.handlerClickButton })
Scroll() {
Column() {
Row() {
Column() {
Text('蓝牙')
.fontSize(30)
.margin({ top: 20 })
.alignSelf(ItemAlign.Start)
if (true == this.isOn) {
Text('发现')
.fontSize(20)
.alignSelf(ItemAlign.Start)
Text("设置当前设备名称:"+ bluetoothManager.setLocalName('蓝牙小车1号'))//设置本地蓝牙名称
.fontSize(20)
.alignSelf(ItemAlign.Start)
Text("当前设备名称为:"+ bluetoothManager.getLocalName())//获取本地蓝牙名称
.fontSize(20)
.alignSelf(ItemAlign.Start)
}
}
Blank()//占满空余空间效果
Column() {
Toggle({ type: ToggleType.Switch, isOn: this.isOn })//开启蓝牙的开关
.selectedColor('#ff2982ea')
.key('toggleBtn')
.onChange((isOn: boolean) => {
if(isOn){
this.isOn=true
this.OpenBluetooth()
} else {
this.isOn=false
this.OffBluetooth()
this.SppInfo=[]//蓝牙设备名字列表
this.SppRssi=[]//蓝牙信号列表
}
})
}
}
.width('90%')
if (this.isOn) {
Divider()
.vertical(false)
.strokeWidth(10)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
Text('蓝牙信号强度')
.fontSize(25)
.fontColor('#ff565555')
.margin({ left: '5%' })
.alignSelf(ItemAlign.Start)
ForEach(this.SppRssi, (item) => {
Row() {
Text("蓝牙信号强度: "+item)
.fontSize(20)
}
.alignSelf(ItemAlign.Start)
.width('100%')
.height(50)
.margin({ left: '5%', top: '1%' })
})
Divider()
.vertical(false)
.strokeWidth(10)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
Text("蓝牙名字列表"+bluetoothManager.getRemoteDeviceName("E4:65:B8:12:BB:1E"))
.fontSize(25)
.fontColor('#ff565555')
.margin({ left: '5%' })
.alignSelf(ItemAlign.Start)
.onClick(() =>{
this.SetBluetoothListen()
// this.connectSppBluetooth()
})
ForEach(this.SppInfo, (item) => {
Row() {
Text("蓝牙名字: ")
.fontSize(20)
}
.alignSelf(ItemAlign.Start)
.width('100%')
.height(50)
.margin({ left: '5%', top: '1%' })
Divider()
.vertical(false)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
})
Divider()
.vertical(false)
.strokeWidth(10)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
Text("BLE设备列表")
.fontSize(25)
.fontColor('#ff565555')
.margin({ left: '5%', bottom: '2%' })
.alignSelf(ItemAlign.Start)
ForEach(this.discoverySppList, (item) => {
Row() {
Text("蓝牙地址: "+item)
.fontSize(20)
Button("连接")
.alignSelf(ItemAlign.Center)
.onClick(() => {
})
}
.alignSelf(ItemAlign.Start)
.width('100%')
.height(50)
.margin({ left: '5%', top: '1%' })
Divider()
.vertical(false)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
})
Divider()//分隔器组件
.vertical(false)
.strokeWidth(10)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
Text("SPP配对设备列表")
.fontSize(25)
.fontColor('#ff565555')
.margin({ left: '5%', bottom: '2%' })
.alignSelf(ItemAlign.Start)
ForEach(this.deviceSppList, (item) => {
Row() {
Text("SPP配对设备: "+item)
.fontSize(20)
Button("断开")
.alignSelf(ItemAlign.Center)
.onClick(() => {
AlertDialog.show({
title: '连接失败',
message: '此操作将会断开该设备的连接',
primaryButton: {
value: $r('app.string.cancel'),
action: () => {
}
},
secondaryButton: {
value: '确认',
action: () => {
}
}
})
})
}
.alignSelf(ItemAlign.Start)
.width('100%')
.height(50)
.margin({ left: '5%', top: '1%' })
Divider()
.vertical(false)
.color('#ffece7e7')
.lineCap(LineCapStyle.Butt)
.margin('1%')
})
}
}
}
.constraintSize({ maxHeight: '85%' })
}
}
}
更多关于蓝牙连接的问题,HarmonyOS 鸿蒙Next新人求助各位大佬救救我的实战教程也可以访问 https://www.itying.com/category-93-b0.html
提供一下这个文件:
更多关于蓝牙连接的问题,HarmonyOS 鸿蒙Next新人求助各位大佬救救我的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
你好,请问解决了吗
一直再试,一直不成功,迷惘中
在HarmonyOS鸿蒙Next中,蓝牙连接问题可能涉及以下几个关键点:
-
权限配置:确保在
config.json
文件中正确配置蓝牙权限,如ohos.permission.USE_BLUETOOTH
和ohos.permission.LOCATION
。 -
蓝牙适配器:使用
BluetoothAdapter
类来管理蓝牙设备。通过BluetoothAdapter.getDefaultAdapter()
获取默认蓝牙适配器实例。 -
设备扫描:使用
BluetoothAdapter.startDiscovery()
方法开始扫描附近的蓝牙设备。扫描结果通过BluetoothDevice
对象返回。 -
设备配对与连接:使用
BluetoothDevice.createBond()
方法进行设备配对。配对成功后,使用BluetoothSocket
进行连接和数据传输。 -
回调处理:注册
BluetoothAdapter.BluetoothStateCallback
和BluetoothDevice.BondStateCallback
等回调接口,处理蓝牙状态变化和设备配对状态。 -
错误处理:在连接过程中,可能会遇到
BluetoothSocket
连接失败或数据传输中断等问题,需通过重试机制或日志记录进行排查。 -
API版本兼容性:确保使用的API版本与设备支持的HarmonyOS版本兼容,避免因API不兼容导致的连接问题。
这些是HarmonyOS鸿蒙Next中处理蓝牙连接问题的关键步骤。