三方应用使用蓝牙功能?

场景描述及使用场景

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

阅读 453
1 个回答

使用的核心API

import access from '@ohos.bluetooth.access';
access.getState();
access.enableBluetooth(); // 打开蓝牙
access.disableBluetooth();
connection.setBluetoothScanMode();
connection.startBluetoothDiscovery();
connection.getRemoteDeviceName();

核心代码解释

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);
  }
}

注明版本信息

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

实现效果

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进