【鸿蒙南向开发】手写一个简单的OpenHarmony蓝牙应用

199 篇文章 0 订阅
198 篇文章 0 订阅

前言

此文件就是介绍 OpenHarmony 中的蓝牙接口和如何自己开发一个简单的蓝牙应用程序。

OpenHarmony 蓝牙接口简介

在这里插入图片描述
在这里插入图片描述

getState

enum BluetoothState {
   /** Indicates the local Bluetooth is off */
   STATE_OFF = 0,
   /** Indicates the local Bluetooth is turning on */
   STATE_TURNING_ON = 1,
   /** Indicates the local Bluetooth is on, and ready for use */
   STATE_ON = 2,
   /** Indicates the local Bluetooth is turning off */
   STATE_TURNING_OFF = 3,
   /** Indicates the local Bluetooth is turning LE mode on */
   STATE_BLE_TURNING_ON = 4,
   /** Indicates the local Bluetooth is in LE only mode */
   STATE_BLE_ON = 5,
   /** Indicates the local Bluetooth is turning off LE only mode */
   STATE_BLE_TURNING_OFF = 6

setBluetoothScanMode

enum ScanMode {
   /** Indicates the scan mode is none */
   SCAN_MODE_NONE = 0,
   /** Indicates the scan mode is connectable */
   SCAN_MODE_CONNECTABLE = 1,
   /** Indicates the scan mode is general discoverable */
   SCAN_MODE_GENERAL_DISCOVERABLE = 2,
   /** Indicates the scan mode is limited discoverable */
   SCAN_MODE_LIMITED_DISCOVERABLE = 3,
   /** Indicates the scan mode is connectable and general discoverable */
   SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE = 4,
   /** Indicates the scan mode is connectable and limited discoverable */
   SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE = 5
}

OpenHarmony 典蓝牙配对流程

在这里插入图片描述

1.开启蓝牙

//开蓝牙
ListItem() {
    TitleComponent({ 
        title: "enableBluetooth",                                                            //显示功能的名称
        bgColor: this.currentClick === 0 ? $r('app.color.font_color_007DFF') :  $r('app.color.white_bg_color')
    });                                                                                     //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })   
    .onClick(() => {                                                                        //点击事件                
    if (this.btEnable) {                                                                    //判断蓝牙是否已经打开
        this.message = '蓝牙已经使能';                                                  
        return;
    }
    let ret = BluetoothModel.enableBluetooth();                                             //打开蓝牙
    this.btEnable = ret;                                                               //如果启用了蓝牙,则返回true,否则返回false
    AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);                                 //存储蓝牙打开的结果,方便调用
    AppStorage.SetOrCreate('currentClick', this.currentClick);
    this.message = "蓝牙使能执行结果:" + ret;                                                   //输出结果
})

2.设置发现模式

ListItem() {
    TitleComponent({
        title: "setBluetoothScanMode",                                                       //显示功能的名称
        bgColor: this.currentClick === 6 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                      //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                         //点击事件   
    this.currentClick = 6;
    if (this.btEnable) {                                                                     //判断蓝牙是否已经打开 
        retObj = {mod: 0, duration: -1}                                  //mode表示要设置的蓝牙扫描模式{@link ScanMode}。                                                                                  //*@param duration指示主机可发现的持续时间(秒)。
        setLocalNameRet = BluetoothModel.setBluetoothScanMode(mode, dur);
        if (setLocalNameRet) {
            AppStorage.SetOrCreate('setScanModeRet', setLocalNameRet);
            retObj.mod = mode;
            retObj.duration = dur; 
        } else {                                                          //如果设置了蓝牙扫描模式,返回true,否则返回false。
            console.info("BluetoothModel.setBluetoothScanMode failed!")
            onsole.info("BluetoothModel.setBluetoothScanMode success!", retObj)             
            this.message = "setBluetoothScanMode执行" + this.setLocalNameRet ? '成功' : '失败';
        } 
    }else {
        this.message = "蓝牙未使能";
    }
})


3.注册 pinRequest

ListItem() {
    TitleComponent({
        title: "btPinRequired"                                                                //显示功能的名称
        bgColor: this.currentClick === 18 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                       //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                            //点击事件
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = "蓝牙未使能"; 
        return;
    }
    if (this.isPinRequiredClick) {                                                //判断监听是否开启,即为一个“开关”,并存储数据
        bluetooth.off('pinRequired', () => {                                   
        })
        this.message = 'on:pinRequired监听已关闭,再次点击将开启监听';
        this.isPinRequiredClick = false;
        AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
        return;
    }
    this.isPinRequiredClick = true;
    AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);                //type要侦听的配对请求事件的类型为:pinRequired
    this.pinMessage = 'PIN: ';
    bluetooth.on('pinRequired', (data) => {                                           //callback回调用于侦听配对请求事件。
        this.pinMessage = 'PIN: ';
        this.pinMessage += data.pinCode;
    })
    this.message = 'on:pinRequired监听已启动,再次点击将关闭监听。';
})


4.配对设备

ListItem() {
    TitleComponent({ 
        title: "pairDevice",                                                                   //显示功能的名称  
        bgColor: this.currentClick === 10 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                        //点击后颜色变化
} 
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {                                                                         //点击事件
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = '蓝牙未使能';
        return;
    }
    if (this.deviceId == '') {                                                      //deviceId为要配对的远程设备的地址
        this.message = "请输入目标设备的MAC";                                          //若为空,请输入目标MAC
        return;
    } else {
        this.pairDevice(this.deviceId);                                          //如果配对过程已启动,则返回true,否则返回false
    }
})

OpenHarmony 经典蓝牙设备发现流程

在这里插入图片描述

1.开启蓝牙(同上)
2.设置发现模式(同上)
3.开始蓝牙发现

ListItem() {
    TitleComponent({
        title: "startBluetoothDiscovery",                                                              //显示功能的名称  
        bgColor: this.currentClick === 8 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
    });                                                                                                //点击后颜色变化
}
.padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
    .onClick(() => {//点击事件
    LogUtil.info(this.TAG_PAGE + 'startBluetoothDiscovery 111');
    if (!this.btEnable) {                                                                   //判断蓝牙是否已经打开 
        this.message = '蓝牙未使能';
        return;
    }
    Router.push({ uri: PAGE_URI_DEVICE_FOUND_MODE });                                      //搜索发现蓝牙的分界面
})


4.搜索发现蓝牙的分界面

Scroll() {
    Column() {
        if (this.isOn) {
            PairedDeviceComponent({                                                      //显示已配对的设备
                controller: this.deviceController
            })
            AvailableDeviceComponent({                                                   //显示可被配对的设备                      
                controller: this.deviceController 
            })
        }
    }
    .width(ConfigData.WH_100_100)
}


//PairedDeviceComponent

build() {
    Column() {
        if (this.pairedDevices && this.pairedDevices.length > 0) {
            // paired devices title
            Row() {
                Text($r('app.string.bluetooth_paired_devices'))                          //已配对的设备
                    .fontSize($r('app.float.font_14'))
                    .fontColor($r('app.color.font_color_182431'))
            }
            .width(ConfigData.WH_100_100)
                .padding({
                left: $r('app.float.distance_24'),
                top: $r('app.float.distance_19_5'),
                bottom: $r('app.float.distance_9_5')
            })
            List() {
                // paired devices list
                ForEach(this.pairedDevices, (item: BluetoothDevice, index: number) => {
                    ListItem() {
                        Row() {
                            PairedItem({
                                name: item.deviceName,
                                type: item.deviceType,
                                state: item.connectionState.toString(),
                                mac: item.deviceId
                            })
                        }
                        .width(ConfigData.WH_100_100)
                            .borderRadius($r("app.float.radius_24"))
                            .padding($r('app.float.distance_4'))
                            .backgroundColor($r("app.color.white_bg_color"))
                            .onClick(() => {
                            this.itemClicked(item);
                        })
                    }
                }, item => JSON.stringify(item));
            }
            .height(200)
                .divider({
                strokeWidth: 1,
                color: $r('app.color.color_E3E3E3_grey'),
                startMargin: $r('app.float.wh_value_52'),
                endMargin: $r('app.float.wh_value_12')
            })
                .backgroundColor($r("app.color.white_bg_color"))
                .borderRadius($r("app.float.radius_24"))
        }
    }
}

//AvailableDeviceComponent

build() {
    Column() {
        Row() {
            // available devices title
            Text($r('app.string.bluetooth_available_devices'))                            //可用设备
                .fontSize($r('app.float.font_14'))
                .fontColor($r('app.color.font_color_182431'))
                .width(ConfigData.WH_100_100)
                .padding({
                left: $r('app.float.distance_24'),
                top: $r('app.float.distance_19_5'),
                bottom: $r('app.float.distance_9_5')
            })
            Blank()

            // bluetooth discovering
            if (this.isDeviceDiscovering) {
                DiscoveringAnimatorComponent()
            }
        }
        .width(ConfigData.WH_100_100)

        if (this.availableDevices && this.availableDevices.length >= 1) {
            Scroll() {
                List() {
                    // paired devices list
                    ForEach(this.availableDevices, (item: BluetoothDevice) => {
                        ListItem() {
                            Row() {
                                AvailableItem({
                                    name: item.deviceName,
                                    type: item.deviceType,
                                    state: item.connectionState.toString(),
                                    mac: item.deviceId
                                })
                            }
                            .width(ConfigData.WH_100_100)
                                .borderRadius($r("app.float.radius_24"))
                                .padding($r('app.float.distance_4'))
                                .backgroundColor($r("app.color.white_bg_color"))
                                .onClick(() => {
                                LogUtil.info(this.TAG_PAGE + 'item on click : ' + JSON.stringify(item));
                                AppStorage.SetOrCreate('pairedMac', item.deviceId);
                                //                AppStorage.SetOrCreate('pairedName', item.deviceName);
                                this.pairDevice(item)
                            })
                        }
                    }, item => JSON.stringify(item));
                }
                .backgroundColor($r("app.color.white_bg_color"))
                    .borderRadius($r("app.float.radius_24"))
                    .height("80%")
                    .divider({
                    strokeWidth: 1,
                    color: $r('app.color.color_E3E3E3_grey'),
                    startMargin: $r('app.float.wh_value_52'),
                    endMargin: $r('app.float.wh_value_12')
                })
            }
            .scrollBar(BarState.Auto)
                .scrollBarWidth(20)
        } else {
            Row() {
                // Scanning...
                Text($r('app.string.scanning'))
                    .fontSize($r('app.float.font_20'))
                    .textCase(TextCase.UpperCase);
            }
        }
    }
}

整体代码

├─Component
│   │  └─controller
│   ├─pageTitle.ets
│   ├─headComponent.ets
│   └─titleComponent.ets
├─MainAbility
│  ├─controller
│  ├─model
│      ├─BluetoothDevice.ts
│      └─BluetoothModel.ts
│  └─pages
│      ├─homePage.ets
│      └─deviceFound.ets
└─Utils

page

//homePage
build() {
    Column() {
        GridContainer({
            columns: 12,
            sizeType: SizeType.Auto,
            gutter: vp2px(1) === 2 ? '12vp' : '0vp',
            margin: vp2px(1) === 2 ? '24vp' : '0vp'
        }) {
            Row({}) {
                Column() {
                }
                .width(ConfigData.WH_100_100)
                    .height(ConfigData.WH_100_100)
                    .useSizeType({
                    xs: { span: 0, offset: 0 }, sm: { span: 0, offset: 0 },
                    md: { span: 0, offset: 0 }, lg: { span: 2, offset: 0 }
                });
                Column() {
                    Text(this.message)
                        .fontSize($r("app.float.font_30"))
                        .lineHeight($r("app.float.lineHeight_41"))
                        .fontWeight(FontWeight.Bold)
                        .fontFamily('HarmonyHeiTi')
                        .textAlign(TextAlign.Start)
                        .width(ConfigData.WH_100_100)
                        .padding({
                        left: $r('app.float.distance_26'),
                        top: $r('app.float.distance_12'),
                        bottom: $r('app.float.distance_17')
                    })
                    Column() {
                        HeadComponent({ headName: $r('app.string.test1'), isActive: true })
                        Scroll() {
                            Column({ space: '12vp' }) {
                                List() {
                                    //开蓝牙
                                    ListItem() {
                                        TitleComponent({
                                            title: "enableBluetooth",
                                            bgColor: this.currentClick === 0 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 0;
                                        if (this.btEnable) {
                                            this.message = '蓝牙已经使能';
                                            return;
                                        }
                                        let ret = BluetoothModel.enableBluetooth();
                                        this.btEnable = ret;
                                        AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);
                                        AppStorage.SetOrCreate('currentClick', this.currentClick);
                                        this.message = "蓝牙使能执行结果:" + ret;
                                    })
                                    //设置状态
                                    ListItem() {
                                        TitleComponent({
                                            title: "getState",
                                            bgColor: this.currentClick === 2 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 2;
                                        let ret = BluetoothModel.getState();
                                        switch (ret) {
                                            case 0:
                                                this.stateBT = 'STATE_OFF';
                                                break;
                                            case 1:
                                                this.stateBT = 'STATE_TURNING_ON';
                                                break;
                                            case 2:
                                                this.stateBT = 'STATE_ON';
                                                break;
                                            case 3:
                                                this.stateBT = 'STATE_TURNING_OFF';
                                                break;
                                            case 4:
                                                this.stateBT = 'STATE_BLE_TURNING_ON';
                                                break;
                                            case 5:
                                                this.stateBT = 'STATE_BLE_ON';
                                                break;
                                            case 6:
                                                this.stateBT = 'STATE_BLE_TURNING_OFF';
                                                break;
                                            default:
                                                this.stateBT = '未知状态';
                                                break;
                                        }
                                        this.message = "当前蓝牙的状态是:" + this.stateBT;
                                    })
                                    //设置本地名称  
                                    ListItem() {
                                        TitleComponent({
                                            title: "setLocalName",
                                            bgColor: this.currentClick === 4 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 4;
                                        if (this.btEnable) {
                                            Router.push({ uri: PAGE_URI_DEVICE_NAME });
                                            this.message = "设置SCAN MODE " + this.setScanModeRet ? '成功' : '失败';
                                        } else {
                                            this.message = "蓝牙未使能";
                                        }
                                    })
                                    //设置扫描模式   
                                    ListItem() {
                                        TitleComponent({
                                            title: "setBluetoothScanMode",
                                            bgColor: this.currentClick === 6 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 6;
                                        if (!this.btEnable) {
                                            Router.push({ uri: PAGE_URI_SET_SCAN_MODE });
                                            this.message = "setBluetoothScanMode执行" + this.setLocalNameRet ? '成功' : '失败';
                                        } else {
                                            this.message = "蓝牙未使能";
                                        }
                                    })
                                    // 开始蓝牙发现
                                    ListItem() {
                                        TitleComponent({
                                            title: "startBluetoothDiscovery",
                                            bgColor: this.currentClick === 8 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        LogUtil.info(this.TAG_PAGE + 'startBluetoothDiscovery 111');
                                        if (this.btEnable) {
                                            this.message = '蓝牙未使能';
                                            return;
                                        }
                                        this.currentClick = 8;
                                        Router.push({ uri: PAGE_URI_DEVICE_FOUND_MODE });
                                    })
                                    //监听PinRequired
                                    ListItem() {
                                        TitleComponent({
                                            title: this.btPinRequired,
                                            pinRequiredFlag: true,
                                            bgColor: this.currentClick === 18 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        if (!this.btEnable) {
                                            this.message = "蓝牙未使能";
                                            return;
                                        }
                                        if (this.isPinRequiredClick) {
                                            bluetooth.off('pinRequired', () => {

                                            })
                                            this.message = 'on:pinRequired监听已关闭,再次点击将开启监听';
                                            this.isPinRequiredClick = false;
                                            this.btPinRequired = 'on:pinRequired';
                                            AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
                                            return;
                                        }
                                        this.isPinRequiredClick = true;
                                        this.currentClick = 18;
                                        this.btPinRequired = 'off:pinRequired';
                                        AppStorage.SetOrCreate('on_pinRequired', this.btPinRequired);
                                        this.pinMessage = 'PIN: ';
                                        bluetooth.on('pinRequired', (data) => {
                                            this.pinMessage = 'PIN: ';
                                            this.pinMessage += data.pinCode;
                                        })
                                        this.message = 'on:pinRequired监听已启动,再次点击将关闭监听。';
                                    })
                                    //配对设备
                                    ListItem() {
                                        TitleComponent({
                                            title: "pairDevice",
                                            bgColor: this.currentClick === 10 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 10;
                                        if (!this.btEnable) {
                                            this.message = '蓝牙未使能';
                                            return;
                                        }
                                        if (this.deviceId == '') {
                                            this.message = "请输入目标设备的MAC";
                                            return;
                                        } else {
                                            this.pairDevice(this.deviceId);
                                        }
                                    })
                                    //关蓝牙
                                    ListItem() {
                                        TitleComponent({
                                            title: "disableBluetooth",
                                            bgColor: this.currentClick === 1 ? $r('app.color.font_color_007DFF') : $r('app.color.white_bg_color')
                                        });
                                    }
                                    .padding({ top: $r('app.float.distance_2'), bottom: $r('app.float.distance_2') })
                                        .onClick(() => {
                                        this.currentClick = 1;
                                        if (!this.btEnable) {
                                            this.message = '蓝牙还未使能';
                                            return;
                                        }
                                        let ret = BluetoothModel.disableBluetooth();
                                        this.btEnable = false;
                                        AppStorage.SetOrCreate('bluetoothIsOn', this.btEnable);
                                        this.message = "蓝牙去使能执行结果:" + ret;
                                    })
                                }
                            }
                            .width(ConfigData.WH_100_100)
                                .height(600)
                        }
                        .scrollable(ScrollDirection.Vertical).scrollBar(BarState.On)
                        .scrollBarColor(Color.Gray).scrollBarWidth(30)
                    }
                    .padding({ left: $r('app.float.distance_2'), right: $r('app.float.distance_2') })
                    .width(ConfigData.WH_100_100)
                    .height(ConfigData.WH_100_100)
                    .useSizeType({
                    xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
                    md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
                    });
                }
                .padding({ left: $r('app.float.distance_2'), right: $r('app.float.distance_2') })
                .width(ConfigData.WH_100_100)
                .height(ConfigData.WH_100_100)
                .useSizeType({
                xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
                md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
                });
            }
            .width(ConfigData.WH_100_100)
            .height(ConfigData.WH_100_100);
        }
        .backgroundColor($r("sys.color.ohos_id_color_sub_background"))
        .width(ConfigData.WH_100_100)
        .height(ConfigData.WH_100_100);
    }
}

component:

// titlecomoponent

import ConfigData from '../Utils/ConfigData';
@Component
export struct TitleComponent{
    private title:string | Resource;
    private fontSize:string ='35vp';
    private stateChangeFlag: boolean = false;
    private pinRequiredFlag: boolean = false;
    private bondStateChangeFlag: boolean = false;
    @State isTouched:boolean = false;
    @State bgColor: Resource = $r('app.color.font_color_007DFF');
    @StorageLink('on_stateChange') state: string = 'on:stateChange';
    @StorageLink('on_pinRequired') pin: string = 'on:pinRequired';
    @StorageLink('on_bondStateChange') bondState: string = 'on:bondStateChange';
    build(){
        Column(){
            Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems:ItemAlign.Center }) {
                Text(this.stateChangeFlag ? this.state : (this.pinRequiredFlag ? this.pin : (this.bondStateChangeFlag ? this.bondState : this.title)))
                    .textAlign(TextAlign.Center)
                    .width("100%")
                    .height(100)
                    .fontSize(this.fontSize)
                    .fontColor($r('app.color.font_color_182431'))
                    .fontWeight(FontWeight.Medium)
            }
            .height(ConfigData.WH_100_100)
                .width(ConfigData.WH_100_100)
                .backgroundColor(this.bgColor)
                .linearGradient(this.isTouched ? {
                angle: 90,
                direction: GradientDirection.Right,
                colors: [[$r("app.color.DCEAF9"), 0.0], [$r("app.color.FAFAFA"), 1.0]]
            } : {
                angle: 90, direction: GradientDirection.Right,
                colors: [[$r("sys.color.ohos_id_color_foreground_contrary"), 1], [$r("sys.color.ohos_id_color_foreground_contrary"), 1]]})
                .onTouch((event: TouchEvent) => {
                if (event.type === TouchType.Down) {
                    this.isTouched = true;
                }
                if (event.type === TouchType.Up) {
                    this.isTouched = false;
                }
            })
        }
        .padding($r('app.float.distance_4'))
        .height("100vp")
        .borderRadius($r('app.float.radius_12'))
    }
}

model:

import { DeviceState } from './BluetoothModel'
export class Profile {
    profileId: number = -1;
    profileConnectionState: number = -1
    constructor() {
    }
}
/**
 * Bluetooth device class
 */
export default class BluetoothDevice {
    deviceId: string = '';
    deviceName: string = '';
    deviceType: string = '';
    connectionState: number = 0;
    profiles: Map<number, Profile> = new Map();
    constructor() {
    }
    setProfiles(data: Array<{
    	profileId: number;
    	profileConnectionState: number;
    }>): void{
        	data.forEach((item: {
        	profileId: number;
        	profileConnectionState: number;
    	}) => {
        	this.setProfile({
            	profileId: item.profileId,
            	deviceId: this.deviceId,
            	profileConnectionState: item.profileConnectionState
        	})
    	})
	}
	setProfile(data: {
		profileId: number;
        deviceId: string;
        profileConnectionState: number;
    }): void{
    	if (this.deviceId !== data.deviceId) {
        	return;
    	}
    	this.profiles.set(data.profileId, data)
    	let countStateDisconnect = 0;
		let countStateConnecting = 0;
		let countStateConnected = 0;
		let countStateDisconnecting = 0;
		this.profiles.forEach((profile, key) => {
    		if (profile.profileConnectionState == 0) {
        		// 0:the current profile is disconnected
        		countStateDisconnect++;
    		} else if (profile.profileConnectionState == 1) {
        		// 1:the current profile is being connected
       		 countStateConnecting++;
    		} else if (profile.profileConnectionState == 2) {
        		// 2:the current profile is connected
        	countStateConnected++;
    		} else if (profile.profileConnectionState == 3) {
        		// 3:the current profile is being disconnected
        		countStateDisconnecting++;
    		}
		});
		if (countStateConnected > 0 || countStateDisconnecting > 0) {
    		this.connectionState = DeviceState.STATE_CONNECTED;
		} else if (countStateConnecting > 0) {
    		this.connectionState = DeviceState.STATE_CONNECTING;
		} else {
    		this.connectionState = DeviceState.STATE_DISCONNECTED;
		}
	}
}

预览图

在这里插入图片描述

写在最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)用来跟着学习是非常有必要的。

这份鸿蒙(HarmonyOS NEXT)文档包含了鸿蒙开发必掌握的核心知识要点,内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、OpenHarmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

希望这一份鸿蒙学习文档能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

获取这份完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习文档

鸿蒙(HarmonyOS NEXT)5.0最新学习路线

在这里插入图片描述

有了路线图,怎么能没有学习文档呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习文档

《鸿蒙 (OpenHarmony)开发入门教学视频》

在这里插入图片描述

《鸿蒙生态应用开发V3.0白皮书》

在这里插入图片描述

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

在这里插入图片描述

《鸿蒙开发基础》

●ArkTS语言
●安装DevEco Studio
●运用你的第一个ArkTS应用
●ArkUI声明式UI开发
.……
在这里插入图片描述

《鸿蒙开发进阶》

●Stage模型入门
●网络管理
●数据管理
●电话服务
●分布式应用开发
●通知与窗口管理
●多媒体技术
●安全技能
●任务管理
●WebGL
●国际化开发
●应用测试
●DFX面向未来设计
●鸿蒙系统移植和裁剪定制
……
在这里插入图片描述

《鸿蒙进阶实战》

●ArkTS实践
●UIAbility应用
●网络案例
……
在这里插入图片描述

获取以上完整鸿蒙HarmonyOS学习文档,请点击→纯血版全套鸿蒙HarmonyOS学习文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值