文档开发者中心
我的
|

UI

App开发

HarmonyOS 6

HarmonyOS 5

鸿蒙应用开发低功耗蓝牙BLE的功能讲解和DEMO源码

鸿蒙应用开发低功耗蓝牙BLE的功能讲解和DEMO源码
点赞
1
收藏
回复
1
分享
举报
浏览104 发布于2025-12-22 08:40四川
全部评论
最多点赞
最新发布
最早发布

cke_128.pngcke_1026.png

一、结论

此项目实际上是从官方文档基础上进行了扩展。文档所示例的样本代码比较割裂,只是针对API功能的讲解,在不知道BLE完成业务流程的基础上,我们是不清楚如何调用的。在鸿蒙中主要通过ble这个系统能力进行低功耗蓝牙的实现。

项目整个框架采用管理对象进行BLE功能的封装:

GattServermanager
作为GATT服务器(周边设备)的管理类,实现服务器的初始化和服务的注册。

GattClientManager
作为周边设备客户端管理类,实现链接和数据读写传递。

BleScanManager
作为BLE扫描管理类,实现扫描和结果的处理。

BleAdvertisingManager
作为BLE广播类,实现广播的处理,特征值和描述符的生成。

BLEMgr
作为总管理类,业务逻辑的感知层,业务直接调用BLEMgr实现低功耗蓝牙接口的调用。

二、代码实现和详细解释

HaronyOS+BLE蓝牙DEMO
实现了BLE蓝牙完整的交互过程:
1.管理蓝牙的开启和关闭
2.外围设备的服务创建,广播等
3.中央设备的扫描,链接,读取特征和描述等

Index.ets 启动页

收起
自动换行
深色代码主题
复制
import { CommonTextModifier } from '../common/CommonTextModifier'
import { BLEMgr } from '../mgr/BLEMgr';
import { promptAction } from '@kit.ArkUI';
import { PermissionsUtil } from '../utils/PermissionsUtil';

@Entry
@Component
struct Index {

  @State isOpenBluetooth: boolean = false;

  private mBLEMgr: BLEMgr = new BLEMgr();
  txtModifier: CommonTextModifier = new CommonTextModifier()

  async aboutToAppear() {
    let isHave: boolean = await PermissionsUtil.requestPermission();
    if(isHave){
      this.isOpenBluetooth = this.mBLEMgr.getBluetoothState();
    }else{
      this.toSysSettingPage();
    }
  }

  private toSysSettingPage(){
    globalThis.sysContext.startAbility({
      bundleName: 'com.huawei.hmos.settings',
      abilityName: 'com.huawei.hmos.settings.MainAbility',// com.huawei.hmos.settings.AppInfoAbility
      uri: 'application_info_entry', //application_settings   application_info_entry
      parameters: {
        pushParams: globalThis.sysContext.abilityInfo.bundleName // 应用包名com.example.tosettingdemo  'uiAbilityContext.abilityInfo.bundleName'
      }
    });
  }

  onClickStart = async ()=>{
    let isHave: boolean = await PermissionsUtil.requestPermission();
    if(isHave){
      this.mBLEMgr.startBluetooth((str: string)=>{
        let content: string = "";
        if (str == 'STATE_ON') {
          content = "蓝牙已开启";
        }else{
          content = "开启错误:" + str;
        }
        promptAction.showToast({
          message: content
        });
      });
    }else{
      this.toSysSettingPage();
    }
  }

  onClickClose = async ()=>{
    let isHave: boolean = await PermissionsUtil.requestPermission();
    if(isHave){
      this.mBLEMgr.closeBluetooth((str: string)=>{
        let content: string = "";
        if (str == 'STATE_OFF') {
          content = "蓝牙已关闭";
        }else{
          content = "关闭错误:" + str;
        }
        promptAction.showToast({
          message: content
        });
      });
    }else{
      this.toSysSettingPage();
    }
  }

  onClickStartAdv = ()=>{
    this.mBLEMgr.startAdvertising((advState: string)=>{
      let content: string = "";
      if(advState == "STARTED"){
        content = "广播已开启";
      }else{
        content = "广播错误:" + advState;
      }
      promptAction.showToast({
        message: content
      });
    });
  }

  onClickCloseAdv = ()=>{
    this.mBLEMgr.stopAdvertising((str: string)=>{
      promptAction.showToast({
        message: str
      });
    });
  }

  onClickStartScan = ()=>{
    this.mBLEMgr.startScan();
  }

  onClickCloseScan = ()=>{
    this.mBLEMgr.stopScan();
  }

  onClickStartServer = ()=>{
    this.mBLEMgr.registerServer((res: string)=>{
      promptAction.showToast({
        message: res
      });
    });
  }

  onClickCloseServer = ()=>{
    this.mBLEMgr.unRegisterServer((res: string)=>{
      promptAction.showToast({
        message: res
      });
    });
  }

  @Builder LineView(){
    Line().width("100%").height(px2vp(2)).backgroundColor(Color.Black).margin({
      top: px2vp(100)
    })
  }

  build() {
    Column() {

      Column(){
        Text(this.isOpenBluetooth ? "蓝牙状态: 已开启" : "蓝牙状态: 已关闭")
        Text("蓝牙设备名:" + this.mBLEMgr.getCurrentDeviceName())
      }

      Text("开启蓝牙")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickStart)

      Text("关闭蓝牙")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickClose)

      this.LineView()

      Text("启动服务")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickStartServer)

      Text("关闭服务")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickCloseServer)

      Text("开启广播")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickStartAdv)

      Text("关闭广播")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickCloseAdv)

      this.LineView()

      Text("开启扫描")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickStartScan)

      Text("关闭扫描")
        .attributeModifier(this.txtModifier)
        .onClick(this.onClickCloseScan)

    }
    .height('100%')
    .width('100%')
  }
}




BLEMgr.ets

收起
自动换行
深色代码主题
复制
import bleAdvertisingManager from "./BleAdvertisingManager";
import bleScanManager from "./BleScanManager";
import { access } from '@kit.ConnectivityKit';
import gattServerManager from "./GattServerManager";
import { connection } from '@kit.ConnectivityKit';
import { BusinessError } from "@kit.BasicServicesKit";

const TAG: string = "BLEMgr";

export class BLEMgr {

  public getBluetoothState(): boolean {
    let state = access.getState();
    return this.getStateName(state) == "STATE_ON" ? true : false;
  }

  /**
   * 当前设备蓝牙设备名称
   */
  public getCurrentDeviceName(){
    let localName: string = "";
    try {
      localName = connection.getLocalName();
      console.info(TAG, 'getCurrentDeviceName localName: ' + localName);
    } catch (err) {
      console.error(TAG, 'getCurrentDeviceName errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
    return localName;
  }

  /**
   * 蓝牙广播状态
   * @param state
   * @returns
   */
  public getAdvState(state: number){
    switch (state) {
      case 1:
        // 首次启动广播后的状态。
        return 'STARTED';
      case 2:
        // 临时启动广播后的状态。
        return 'ENABLED';
      case 3:
        // 临时停止广播后的状态。
        return 'DISABLED';
      case 4:
        // 完全停止广播后的状态。
        return 'STOPPED';
      default:
        return 'unknown status';
    }
  }

  /**
   * 蓝牙开启状态
   * @param state
   * @returns
   */
  private getStateName(state: number): string {
    switch (state) {
      case 0:
        // 蓝牙已关闭。
        return 'STATE_OFF'; ;
      case 1:
        // 蓝牙正在打开。
        return 'STATE_TURNING_ON';
      case 2:
        // 蓝牙已打开。
        return 'STATE_ON';
      case 3:
        // 蓝牙正在关闭。
        return 'STATE_TURNING_OFF';
      case 4:
        // 蓝牙正在打开LE-only模式。
        return 'STATE_BLE_TURNING_ON';
      case 5:
        // 蓝牙正处于LE-only模式。
        return 'STATE_BLE_ON';
      case 6:
        // 蓝牙正在关闭LE-only模式。
        return 'STATE_BLE_TURNING_OFF';
      default:
        return 'unknown status';
    }
  }

  /**
   * 开启蓝牙
   */
  public startBluetooth(callback: (str: string)=> void){
    try {
      access.enableBluetooth();
    } catch (err) {
      let errStr: string = JSON.stringify(err);
      console.info(TAG, 'startBluetooth enableBluetooth err: ' + errStr);
      callback(errStr);
    }
    access.on('stateChange', (data) => {
      let btStateMessage = this.getStateName(data);
      callback(btStateMessage);
      if (btStateMessage == 'STATE_ON') {
        access.off('stateChange');
      }
      console.info('bluetooth statues: ' + btStateMessage);
    });
  }

  /**
   * 关闭蓝牙
   */
  public closeBluetooth(callback: (str: string)=> void){
    access.disableBluetooth();
    access.on('stateChange', (data) => {
      let btStateMessage = this.getStateName(data);
      callback(btStateMessage);
      if (btStateMessage == 'STATE_OFF') {
        access.off('stateChange');
      }
      console.info("bluetooth statues: " + btStateMessage);
    })
  }

  /**
   * 创建GATT服务器,注册服务
   */
  public registerServer(callBack: (str: string)=> void){
    gattServerManager.registerServer(callBack);
  }

  /**
   * 删除服务,关闭GATT服务器
   */
  public unRegisterServer(callBack: (str: string)=> void){
    gattServerManager.unRegisterServer(callBack);
  }

  /**
   * 开启广播
   */
  public async startAdvertising(callBack: (state: string)=> void) {
    await bleAdvertisingManager.startAdvertising((state: number)=>{
      let advState: string = this.getAdvState(state);
      callBack(advState);
    });
  }

  /**
   * 关闭广播
   */
  public async stopAdvertising(callBack: (str: string)=> void) {
    await bleAdvertisingManager.stopAdvertising(callBack);
  }

  /**
   * 开始扫描
   */
  public startScan() {
    bleScanManager.startScan();
  }

  /**
   * 关闭扫描
   */
  public stopScan() {
    bleScanManager.stopScan();
  }


}

GattServermanager.ets

收起
自动换行
深色代码主题
复制
import { ble } from '@kit.ConnectivityKit';
import { constant } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';

const TAG: string = 'GattServerManager';

export class GattServerManager {
  gattServer: ble.GattServer | undefined = undefined;
  connectState: ble.ProfileConnectionState = constant.ProfileConnectionState.STATE_DISCONNECTED;
  myServiceUuid: string = '00001810-0000-1000-8000-00805F9B34FB';
  myCharacteristicUuid: string = '00001820-0000-1000-8000-00805F9B34FB';
  myFirstDescriptorUuid: string = '00002902-0000-1000-8000-00805F9B34FB'; // 2902一般用于notification或者indication
  mySecondDescriptorUuid: string = '00002903-0000-1000-8000-00805F9B34FB';

  // 构造BLEDescriptor
  private initDescriptor(des: string, value: ArrayBuffer): ble.BLEDescriptor {
    let descriptor: ble.BLEDescriptor = {
      serviceUuid: this.myServiceUuid,
      characteristicUuid: this.myCharacteristicUuid,
      descriptorUuid: des,
      descriptorValue: value
    };
    return descriptor;
  }

  // 构造BLECharacteristic
  private initCharacteristic(): ble.BLECharacteristic {
    let descriptors: Array<ble.BLEDescriptor> = [];
    let descBuffer = new ArrayBuffer(2);
    let descValue = new Uint8Array(descBuffer);
    descValue[0] = 31;
    descValue[1] = 32;
    descriptors[0] = this.initDescriptor(this.myFirstDescriptorUuid, new ArrayBuffer(2));
    descriptors[1] = this.initDescriptor(this.mySecondDescriptorUuid, descBuffer);
    let charBuffer = new ArrayBuffer(2);
    let charValue = new Uint8Array(charBuffer);
    charValue[0] = 21;
    charValue[1] = 22;
    let characteristic: ble.BLECharacteristic = {
      serviceUuid: this.myServiceUuid,
      characteristicUuid: this.myCharacteristicUuid,
      characteristicValue: charBuffer,
      descriptors: descriptors
    };
    return characteristic;
  }

  // 1. 订阅连接状态变化事件
  public onGattServerStateChange() {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }
    try {
      this.gattServer.on('connectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => {
        let state = '';
        switch (stateInfo.state) {
          case 0:
            state = 'DISCONNECTED';
            break;
          case 1:
            state = 'CONNECTING';
            break;
          case 2:
            state = 'CONNECTED';
            break;
          case 3:
            state = 'DISCONNECTING';
            break;
          default:
            state = 'undefined';
            break;
        }
        console.info(TAG, 'onGattServerStateChange: device=' + stateInfo.deviceId + ', state=' + state);
      });
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 2. server端注册服务时调用
  public registerServer(callBack: (str: string)=> void) {
    let characteristics: Array<ble.BLECharacteristic> = [];
    let characteristic = this.initCharacteristic();
    characteristics.push(characteristic);
    let gattService: ble.GattService = {
      serviceUuid: this.myServiceUuid,
      isPrimary: true,
      characteristics: characteristics
    };

    console.info(TAG, 'registerServer ' + this.myServiceUuid);
    try {
      this.gattServer = ble.createGattServer(); // 2.1 构造gattServer,后续的交互都需要使用该实例
      this.onGattServerStateChange(); // 2.2 订阅连接状态
      this.gattServer.addService(gattService);
      callBack("服务成功");
    } catch (err) {
      callBack("服务失败:" + JSON.stringify(err));
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 3. 订阅来自gattClient的读取特征值请求时调用
  public onCharacteristicRead() {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }

    console.info(TAG, 'onCharacteristicRead');
    try {
      this.gattServer.on('characteristicRead', (charReq: ble.CharacteristicReadRequest) => {
        let deviceId: string = charReq.deviceId;
        let transId: number = charReq.transId;
        let offset: number = charReq.offset;
        console.info(TAG, 'receive characteristicRead');
        let rspBuffer = new ArrayBuffer(2);
        let rspValue = new Uint8Array(rspBuffer);
        rspValue[0] = 21;
        rspValue[1] = 22;
        let serverResponse: ble.ServerResponse = {
          deviceId: deviceId,
          transId: transId,
          status: 0, // 0表示成功
          offset: offset,
          value: rspBuffer
        };

        try {
          this.gattServer?.sendResponse(serverResponse);
        } catch (err) {
          console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
        }
      });
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 4. 订阅来自gattClient的写入特征值请求时调用
  public onCharacteristicWrite() {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }

    console.info(TAG, 'onCharacteristicWrite');
    try {
      this.gattServer.on('characteristicWrite', (charReq: ble.CharacteristicWriteRequest) => {
        let deviceId: string = charReq.deviceId;
        let transId: number = charReq.transId;
        let offset: number = charReq.offset;
        console.info(TAG, 'receive characteristicWrite: needRsp=' + charReq.needRsp);
        if (!charReq.needRsp) {
          return;
        }
        let rspBuffer = new ArrayBuffer(0);
        let serverResponse: ble.ServerResponse = {
          deviceId: deviceId,
          transId: transId,
          status: 0, // 0表示成功
          offset: offset,
          value: rspBuffer
        };

        try {
          this.gattServer?.sendResponse(serverResponse);
        } catch (err) {
          console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
        }
      });
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 5. 订阅来自gattClient的读取描述符请求时调用
  public onDescriptorRead() {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }

    console.info(TAG, 'onDescriptorRead');
    try {
      this.gattServer.on('descriptorRead', (desReq: ble.DescriptorReadRequest) => {
        let deviceId: string = desReq.deviceId;
        let transId: number = desReq.transId;
        let offset: number = desReq.offset;
        console.info(TAG, 'receive descriptorRead');
        let rspBuffer = new ArrayBuffer(2);
        let rspValue = new Uint8Array(rspBuffer);
        rspValue[0] = 31;
        rspValue[1] = 32;
        let serverResponse: ble.ServerResponse = {
          deviceId: deviceId,
          transId: transId,
          status: 0, // 0表示成功
          offset: offset,
          value: rspBuffer
        };

        try {
          this.gattServer?.sendResponse(serverResponse);
        } catch (err) {
          console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
        }
      });
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 6. 订阅来自gattClient的写入描述符请求时调用
  public onDescriptorWrite() {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }

    console.info(TAG, 'onDescriptorWrite');
    try {
      this.gattServer.on('descriptorWrite', (desReq: ble.DescriptorWriteRequest) => {
        let deviceId: string = desReq.deviceId;
        let transId: number = desReq.transId;
        let offset: number = desReq.offset;
        console.info(TAG, 'receive descriptorWrite: needRsp=' + desReq.needRsp);
        if (!desReq.needRsp) {
          return;
        }
        let rspBuffer = new ArrayBuffer(0);
        let serverResponse: ble.ServerResponse = {
          deviceId: deviceId,
          transId: transId,
          status: 0, // 0表示成功
          offset: offset,
          value: rspBuffer
        };

        try {
          this.gattServer?.sendResponse(serverResponse);
        } catch (err) {
          console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
        }
      });
    } catch (err) {
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }

  // 7. server端删除服务,不再使用时调用
  public unRegisterServer(callBack: (str: string)=> void) {
    if (!this.gattServer) {
      console.error(TAG, 'no gattServer');
      return;
    }

    console.info(TAG, 'unRegisterServer ' + this.myServiceUuid);
    try {
      this.gattServer.removeService(this.myServiceUuid); // 7.1 删除服务
      callBack("关闭服务");
      this.gattServer.off('connectionStateChange', (stateInfo: ble.BLEConnectionChangeState) => { // 7.2 取消订阅连接状态
      });
      this.gattServer.close() // 7.3 如果不再使用此gattServer,则需要close
    } catch (err) {
      callBack("关闭失败:" + JSON.stringify(err));
      console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
    }
  }
}

let gattServerManager = new GattServerManager();
export default gattServerManager as GattServerManager;

其余GattClientManager BleScanManager BleAdvertisingManager 类可以参考官方文档。

ScanResultPage .ets

收起
自动换行
深色代码主题
复制
import { ArrayList, HashMap } from '@kit.ArkTS'
import { BleDeviceInfo } from '../bean/BleDeviceInfo'
import { promptAction } from '@kit.ArkUI';
import { EventHubUtils } from '../utils/EventHubUtils';
import { BLEMgr } from '../mgr/BLEMgr';

@Entry
@Component
struct ScanResultPage {

  private mBLEMgr: BLEMgr = new BLEMgr();
  private mCacheMap: HashMap<string, string> = new HashMap();
  @State connStr: string = "";
  @State optionSelect: number = -1;

  aboutToAppear(): void {
    EventHubUtils.getEventHub().on("ScanRes", this.onScanRes);
    EventHubUtils.getEventHub().on("ConnStateChange", this.onConnStateChange);

  }

  aboutToDisappear(): void {
    EventHubUtils.getEventHub().off("ScanRes", this.onScanRes);
    EventHubUtils.getEventHub().off("ConnStateChange", this.onConnStateChange);
  }

  onConnStateChange = (state: string)=>{
    if(state == "CONNECTING"){
      this.connStr = "连接中";
    }else if(state == "CONNECTED"){
      this.connStr = "已连接";
      // 进行设备的服务查询
      this.mBLEMgr.discoverServices();
    }else if(state == "DISCONNECTING"){
      this.connStr = "断开中";
    }else{
      this.connStr = "断开连接";
      setTimeout(()=>{
        this.optionSelect = -1;
      }, 2000);
    }
  }

  onScanRes = (info: BleDeviceInfo)=>{
    let deviceId: string = info.DeviceData?.deviceId ?? "";
    if(!this.mCacheMap.hasKey(deviceId)){
      this.mCacheMap.set(deviceId, deviceId);
      this.mListDeviceInfo.push(info);
    }
  }

  @State mListDeviceInfo: Array<BleDeviceInfo> = new Array();

  @Builder ListView(){
    List() {
      ForEach(this.mListDeviceInfo, (item: BleDeviceInfo, index: number) => {
        ListItem() {
          Column(){
            Text("设备ID: " + item.DeviceData?.deviceId).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text("设备名: " + item.DeviceData?.deviceName).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text("RSSI: " + item.DeviceData?.rssi).fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            Text(item.DeviceData?.connectable ? "连接状态: 可连接" : "连接状态: 不可连接").fontSize(px2fp(52)).fontColor(Color.White).width('100%')
            if(this.optionSelect == index){
              Row(){
                Button(this.connStr).backgroundColor(Color.Yellow).fontColor(Color.Blue)
                  .onClick(()=>{
                    // 断开
                    AlertDialog.show({
                      title:"BLE断开",
                      message:"是否选择" + item.DeviceData?.deviceName + "进行BLE断开?",
                      autoCancel: true,
                      primaryButton: {
                        value:"确定",
                        action:()=>{
                          promptAction.showToast({ message: item.DeviceData?.deviceName + " 断开ing!"});
                          this.mBLEMgr.stopConnect();
                        }
                      },
                      secondaryButton: {
                        value:"取消",
                        action:()=>{
                          promptAction.showToast({ message: "取消!"});
                        }
                      },
                      cancel:()=>{
                        promptAction.showToast({ message: "取消!"});
                      }
                    });
                  })
                if(this.connStr == "已连接"){
                  Button("读取特征值").backgroundColor(Color.Yellow).fontColor(Color.Blue)
                    .onClick(()=>{
                      this.mBLEMgr.getClient().readCharacteristicValue();
                    }).margin({ left: px2vp(10) })

                  Button("读取描述").backgroundColor(Color.Yellow).fontColor(Color.Blue)
                    .onClick(()=>{
                      this.mBLEMgr.getClient().readDescriptorValue();
                    }).margin({ left: px2vp(10) })
                }
              }
              .width("100%")
            }
            Divider().height(px2vp(1)).width("100%")
          }
          .padding({
            left: px2vp(35),
            right: px2vp(35)
          })
          .width('100%')
          .height(px2vp(450))
          .justifyContent(FlexAlign.Start)
          .onClick(()=>{
            // 点击选择处理配对
            AlertDialog.show({
              title:"BLE连接",
              message:"是否选择" + item.DeviceData?.deviceName + "进行BLE连接?",
              autoCancel: true,
              primaryButton: {
                value:"确定",
                action:()=>{
                  promptAction.showToast({ message: item.DeviceData?.deviceName + " 连接ing!"});
                  this.mBLEMgr.startConnect(item.DeviceData?.deviceId);
                  this.optionSelect = index;
                }
              },
              secondaryButton: {
                value:"取消",
                action:()=>{
                  promptAction.showToast({ message: "取消!"});
                }
              },
              cancel:()=>{
                promptAction.showToast({ message: "取消!"});
              }
            });
          })
        }
      }, (item: string, index: number) => JSON.stringify(item) + index)
    }
    .width('100%')
  }

  build() {
    Column() {
      this.ListView()
    }
    .height('100%')
    .width('100%')
    .backgroundColor(Color.Blue)
  }
}
展开全部
1楼回复于2025-12-22 15:20 来自四川
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。