【HarmonyOS】鸿蒙应用蓝牙功能实现(一)

GeorgeGcs
• 阅读 4

##鸿蒙开发能力 ##HarmonyOS SDK应用服务##鸿蒙金融类应用 (金融理财# 前言 蓝牙技术是一种无线通信技术,可以在短距离内传输数据。它是由爱立信公司于1994年提出的,使用2.4 GHz的ISM频段,可以在10米左右的距离内进行通信。可以用于连接手机、耳机、音箱、键盘、鼠标、打印机等各种设备。 特点是低功耗、低成本、简单易用。目前已经发展到了第五代,支持更高的数据传输速率和更广的覆盖范围。 蓝牙实现原理 蓝牙的实现原理是基于无线电技术的短距离通信协议,使用2.4GHz频段的无线电波进行通信,使用频率跳跃技术(Frequency Hopping Spread Spectrum,FHSS)来避免与其他无线设备的干扰。 在通信过程中,蓝牙设备会发送和接收数据包,并且使用不同的蓝牙协议来控制通信流程和数据传输。

蓝牙跳频技术的原理 蓝牙跳频技术主要基于频率跳跃技术,即通过在不同频率上快速跳跃来发送数据。这种技术可以防止干扰和噪声影响数据传输,提高数据传输的可靠性。具体来说,当某条频率受到干扰或噪声时,系统会自动切换到其他频率上进行传输,从而确保数据的完整性和稳定性。 DEMO示例 以下为蓝牙开关和状态控制 import { access } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit';

export class BlueToothMgr {

private static mBlueToothMgr: BlueToothMgr | undefined = undefined;

public Ins(){ if(BlueToothMgr.mBlueToothMgr){ BlueToothMgr.mBlueToothMgr = new BlueToothMgr(); } return BlueToothMgr.mBlueToothMgr; }

// STATE_OFF 0 表示蓝牙已关闭。 // STATE_TURNING_ON 1 表示蓝牙正在打开。 // STATE_ON 2 表示蓝牙已打开。 // STATE_TURNING_OFF 3 表示蓝牙正在关闭。 // STATE_BLE_TURNING_ON 4 表示蓝牙正在打开LE-only模式。 // STATE_BLE_ON 5 表示蓝牙正处于LE-only模式。 // STATE_BLE_TURNING_OFF 6 表示蓝牙正在关闭LE-only模式。

/**

  • 设置蓝牙访问(开关状态)

  • @param isAccess true: 打开蓝牙

  • / setBlueToothAccess(isAccess: boolean){ try { if(isAccess){

    access.enableBluetooth();
    access.on('stateChange', (data: access.BluetoothState) => {
      let btStateMessage = this.switchState(data);
      if (btStateMessage == 'STATE_ON') {
        access.off('stateChange');
      }
      console.info('bluetooth statues: ' + btStateMessage);
    })

    }else{

    access.disableBluetooth();
    access.on('stateChange', (data: access.BluetoothState) => {
      let btStateMessage = this.switchState(data);
      if (btStateMessage == 'STATE_OFF') {
        access.off('stateChange');
      }
      console.info("bluetooth statues: " + btStateMessage);
    })

    } } catch (err) { console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }

    private switchState(data: access.BluetoothState){ let btStateMessage = ''; switch (data) { case 0:

    btStateMessage += 'STATE_OFF';
    break;

    case 1:

    btStateMessage += 'STATE_TURNING_ON';
    break;

    case 2:

    btStateMessage += 'STATE_ON';
    break;

    case 3:

    btStateMessage += 'STATE_TURNING_OFF';
    break;

    case 4:

    btStateMessage += 'STATE_BLE_TURNING_ON';
    break;

    case 5:

    btStateMessage += 'STATE_BLE_ON';
    break;

    case 6:

    btStateMessage += 'STATE_BLE_TURNING_OFF';
    break;

    default:

    btStateMessage += 'unknown status';
    break;

    } return btStateMessage; } }

import { access } from '@kit.ConnectivityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { BlueToothMgr } from '../manager/BlueToothMgr'; import { abilityAccessCtrl, common } from '@kit.AbilityKit';

@Entry @Component struct Index {

private TAG: string = "BlueToothTest";

// 蓝牙状态 @State isStartBlueTooth: boolean = false; @State userGrant: boolean = false;

async aboutToAppear() { await this.requestBlueToothPermission();

let state = access.getState();
console.log(this.TAG, "getState state: " + state);
if(state == 2){
  this.isStartBlueTooth = true;
}else{
  this.isStartBlueTooth = false;
}

}

// 用户申请权限 async reqPermissionsFromUser(): Promise<number[]> { let context = getContext() as common.UIAbilityContext; let atManager = abilityAccessCtrl.createAtManager(); let grantStatus = await atManager.requestPermissionsFromUser(context, ['ohos.permission.ACCESS_BLUETOOTH']); return grantStatus.authResults; }

// 用户申请蓝牙权限 async requestBlueToothPermission() { let grantStatus = await this.reqPermissionsFromUser(); for (let i = 0; i < grantStatus.length; i++) { if (grantStatus[i] === 0) { // 用户授权,可以继续访问目标操作 this.userGrant = true; } } }

setBlueToothState =()=>{ try { if(!this.isStartBlueTooth){ BlueToothMgr.Ins().setBlueToothAccess(true); }else{ BlueToothMgr.Ins().setBlueToothAccess(false); } let state = access.getState(); if(state == 2){ this.isStartBlueTooth = true; }else{ this.isStartBlueTooth = false; } console.log(this.TAG, "getState state: " + state); } catch (err) { console.error(this.TAG,'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); } }

build() { RelativeContainer() { if(this.userGrant){ Text("蓝牙状态:" + this.isStartBlueTooth ? "开启" : "关闭") .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: 'container', align: VerticalAlign.Center }, middle: { anchor: 'container', align: HorizontalAlign.Center } }) .onClick(this.setBlueToothState) } } .height('100%') .width('100%') } } 加权限配置:

"requestPermissions": [ { "name" : "ohos.permission.ACCESS_BLUETOOTH", "reason": "$string:permission_name", "usedScene": { "abilities": [ "EntryAbility" ], "when":"inuse" } } ] 操作日志:

点赞
收藏
评论区
推荐文章
GeorgeGcs GeorgeGcs
19小时前
【 HarmonyOS 5 入门系列 】鸿蒙HarmonyOS示例项目讲解
【HarmonyOS5入门系列】鸿蒙HarmonyOS示例项目讲解\鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言:移动开发声明式UI框架的技术变革在移动操作系统的发展历程中,UI开发模式经历了从命令式到声明式的重大变革。根据
GeorgeGcs GeorgeGcs
19小时前
【HarmonyOS 5】AttributeModifier和AttributeUpdater区别详解
【HarmonyOS5】AttributeModifier和AttributeUpdater区别详解\鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、AttributeModifier和AttributeUpdater的定义和作用1
GeorgeGcs GeorgeGcs
12小时前
【HarmonyOS 5】鸿蒙跨平台开发方案详解(二)
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、Flutter鸿蒙适配作为最早实现鸿蒙适配的跨平台框架,Flutter在社区推动下已形成较完整的技术方案。当前鸿蒙版Flutter已发布3.22.0ohos版本,该版本基于Flutte
GeorgeGcs GeorgeGcs
10小时前
【HarmonyOS 5】鸿蒙中Stage模型与FA模型详解
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言在HarmonyOS5的应用开发模型中,featureAbility是旧版FA模型(FeatureAbility)的用法,Stage模型已采用全新的应用架构,推荐使用组件化的上下文
GeorgeGcs GeorgeGcs
10小时前
【HarmonyOS 5】鸿蒙星闪NearLink详解
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言鸿蒙星闪NearLinkKit是HarmonyOS提供的短距离通信服务,支持星闪设备间的连接、数据交互。例如,手机可作为中心设备与外围设备(如鼠标、手写笔、智能家电、车钥匙等)通过
GeorgeGcs GeorgeGcs
10小时前
【HarmonyOS NEXT】鸿蒙应用实现手机摇一摇功能
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言手机摇一摇功能,是通过获取手机设备,加速度传感器接口,获取其中的数值,进行逻辑判断实现的功能。在鸿蒙中手机设备传感器@ohos.sensor(传感器)的系统API监听有以下:@oh
GeorgeGcs GeorgeGcs
10小时前
【HarmonyOS 5】桌面快捷方式功能实现详解
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言在移动应用开发中,如何让用户快速触达核心功能,是目前很常见的功能之一。鸿蒙系统提供的桌面快捷方式(Shortcuts)功能,允许开发者为应用内常用功能创建直达入口,用户通过长按应用
GeorgeGcs GeorgeGcs
10小时前
【HarmonyOS 5】鸿蒙中Stage模型与FA模型详解
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、前言在HarmonyOS5的应用开发模型中,featureAbility是旧版FA模型(FeatureAbility)的用法,Stage模型已采用全新的应用架构,推荐使用组件化的上下文
GeorgeGcs GeorgeGcs
8小时前
【HarmonyOS】鸿蒙应用蓝牙功能实现 (二)
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财前言蓝牙一般分为传统蓝牙(BR/EDR),低功耗蓝牙(BLE)两种。鸿蒙将蓝牙的功能模块分的非常细。基本上我们会用到access进行蓝牙状态的开启和关闭,以及状态查询。在使用connect
GeorgeGcs GeorgeGcs
8小时前
【HarmonyOS】鸿蒙应用蓝牙功能实现 (三)
鸿蒙开发能力HarmonyOSSDK应用服务鸿蒙金融类应用(金融理财一、蓝牙配对业务流程1‌.设备进入可被发现模式‌:首先,设备需要进入可被发现模式,这样周围的蓝牙设备才能识别到它。一方设备(如手机)会主动搜索附近的蓝牙设备,并列出所有可用的配对选项。2‌
GeorgeGcs
GeorgeGcs
Lv1
男 · 金融头部企业 · 鸿蒙应用架构师
HarmonyOS认证创作先锋,华为HDE专家,鸿蒙讲师,作者。目前任职鸿蒙应用架构师。 历经腾讯,宝马,研究所,金融。 待过私企,外企,央企。 深耕大应用开发领域十年。 AAE,Harmony(OpenHarmony\HarmonyOS),MAE(Android\IOS),FE(H5\Vue\RN)。
文章
56
粉丝
1
获赞
2