三方应用使用蓝牙功能

三方应用使用蓝牙功能

HarmonyOS
2024-05-20 21:46:39
1879浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
小小肉蟹

把系统使用蓝牙的部分接口用三方应用的形式展示出来,需要使用蓝牙的应用可以从中找到一些需要使用的接口。

使用的核心API

import access from '@ohos.bluetooth.access'; 
access.getState(); 
access.enableBluetooth(); // 打开蓝牙 
access.disableBluetooth(); 
connection.setBluetoothScanMode(); 
connection.startBluetoothDiscovery(); 
connection.getRemoteDeviceName();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

核心代码解释

import connection from '@ohos.bluetooth.connection'; 
import abilityAccessCtrl, { PermissionRequestResult, Permissions } from '@ohos.abilityAccessCtrl'; 
import access from '@ohos.bluetooth.access'; 
import { BusinessError } from '@ohos.base'; 
 
const permissions: Array<Permissions> = ['ohos.permission.ACCESS_BLUETOOTH']; 
 
class bluetoothInfo { 
  deviceName: string; 
  deviceId: string; 
 
  constructor(deviceName: string, deviceId: string) { 
    this.deviceName = deviceName; 
    this.deviceId = deviceId; 
  } 
} 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
  @State @Watch('watch') arr: bluetoothInfo[] = []; 
 
  aboutToAppear(): void { 
    this.reqPermissionsFromUser(permissions); 
  } 
 
  watch() { 
 
  } 
 
  reqPermissionsFromUser(permissions: Array<Permissions>): void { 
    let context: Context = getContext(this) as Context; 
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗 
    atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => { 
      let grantStatus: Array<number> = data.authResults; 
      let length: number = grantStatus.length; 
      for (let i = 0; i < length; i++) { 
        if (grantStatus[i] === 0) { 
          // 用户授权,可以继续访问目标操作 
        } else { 
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限 
          return; 
        } 
      } 
      // 授权成功 
    }).catch((err: BusinessError) => { 
      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
    }) 
  } 
 
  build() { 
    Row() { 
      Column() { 
        Button("打开蓝牙") 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            let state = access.getState() //检测蓝牙开启状态 
            if (state == 0) { 
              access.enableBluetooth(); //打开蓝牙 
            } 
          }) 
        Button("关闭蓝牙") 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .onClick(async () => { 
            let state = access.getState(); //检测蓝牙开启状态 
            if (state == 2) { 
              await access.disableBluetooth(); 
            } 
            this.arr = [] 
            connection.stopBluetoothDiscovery(); 
          }) 
        Button("设置可被扫描") 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .onClick(async () => { 
            let state = access.getState(); //检测蓝牙开启状态 
            if (state == 0) { 
              await access.enableBluetooth(); //打开蓝牙 
            } 
            connection.setBluetoothScanMode(connection.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); 
          }) 
        Button("扫描可连接设备") 
          .fontSize(20) 
          .fontWeight(FontWeight.Bold) 
          .onClick(async () => { 
            let state = access.getState() //检测蓝牙开启状态 
            if (state == 0) { 
              await access.enableBluetooth(); //打开蓝牙 
            } 
            try { 
              connection.on('bluetoothDeviceFind', (data: Array<string>) => { 
                for (let i = 0; i < data.length; i++) { 
                  let name = connection.getRemoteDeviceName(data[i]); 
                  let k = true; 
                  for (let j = 0; j < this.arr.length; j++) { 
                    if (this.arr[j].deviceId == data[i]) { 
                      k = false; 
                      break; 
                    } 
                  } 
                  if (k) { 
                    if (name == "") { 
                      this.arr.push(new bluetoothInfo(data[i], data[i])); 
                    } else { 
                      this.arr.push(new bluetoothInfo(name, data[i])); 
                    } 
                  } 
                } 
                let k = this.arr; 
                console.log('arr data:' + JSON.stringify(this.arr)); 
              }); 
              connection.startBluetoothDiscovery(); 
            } catch (e) { 
              console.log(e); 
            } 
          }) 
 
        List({ space: 20, initialIndex: 0 }) { 
          ForEach(this.arr, (item: bluetoothInfo) => { 
            ListItem() { 
              Text(item.deviceName) 
                .width('100%') 
                .height(100) 
                .fontSize(16) 
                .textAlign(TextAlign.Center) 
                .borderRadius(10) 
                .backgroundColor(0xFFFFFF) 
 
            }.onClick(() => { 
              connection.pairDevice(item.deviceId); 
            }) 
          }) 
        } 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
 
  onReceiveEvent(data: Array<string>) { 
    // for(let i = 0;i<data.length;i++){ 
    //   let name = connection.getRemoteDeviceName(data[i]) 
    //   this.arr.push(new bluetoothInfo(name,data[0])) 
    // } 
    let name = connection.getRemoteDeviceName(data[0]); 
    try { 
      this.onReceiveEvent(data); 
    } catch (e) { 
      console.log(e); 
    } 
    console.log('data length' + data.length); 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.

注明版本信息

只要能用api10的配套版本都能用

实现效果

点击设置可被扫描后,点击扫描可连接设备,设备名称或者设备的地址会使用list打印在下面,点击list中的元素,会提示配对请求。

分享
微博
QQ
微信
回复
2024-05-22 15:34:32


相关问题
三方应用如何获取蓝牙mac地址
3225浏览 • 1回复 待解决
三方应用如何拿到蓝牙mac地址
1242浏览 • 1回复 待解决
HarmonyOS 使用三方应用打开
975浏览 • 1回复 待解决
HarmonyOS 打开三方应用
849浏览 • 1回复 待解决
实现弹幕功能三方
1784浏览 • 1回复 待解决
如何查找三方应用的deeplink
298浏览 • 0回复 待解决
如何将三方应用改为系统应用
2202浏览 • 2回复 已解决
HarmonyOS 唤起到三方的地图应用
822浏览 • 1回复 待解决
三方应用如何获取http代理信息
2668浏览 • 1回复 待解决
怎么使用pdfjs三方库预览pdf文档
3124浏览 • 1回复 待解决
应用内 FFmpeg 开源三方库的编译
2282浏览 • 1回复 待解决
HarmonyOS 第三方应用安装和卸载广播
1343浏览 • 0回复 待解决
HarmonyOS lottie 第三方报错无法使用
987浏览 • 1回复 待解决
求大佬告知如何使用三方cpp库
2816浏览 • 1回复 待解决