【HarmonyOS】鸿蒙应用实现手机摇一摇功能

【HarmonyOS】鸿蒙应用实现手机摇一摇功能

一、前言

手机摇一摇功能,是通过获取手机设备,加速度传感器接口,获取其中的数值,进行逻辑判断实现的功能。

鸿蒙中手机设备传感器@ohos.sensor (传感器)的系统API 监听有以下:
@ohos.sensor (传感器)官网API

  1. 加速度传感器
  2. 环境光传感器
  3. 气压计传感器
  4. 重力传感器
  5. 陀螺仪传感器
  6. 霍尔传感器
  7. 心率传感器
  8. 湿度传感器
  9. 线性加速度传感器
  10. 地磁传感器
  11. 方向传感器
  12. 计步器传感器
  13. 接近光传感器
  14. 旋转矢量传感器
  15. 大幅动作检测传感器
  16. 佩戴检测传感器

其中摇一摇用到的,加速度传感器是多个维度测算 的,是指x、y、z 三个方向上的加速度值。

主要测算一些瞬时加速或减速的动作。比如测量手机的运动速度和方向。

当用户拿着手机运动时,会出现上下摆动的情况,这样可以检测出加速度在某个方向上来回改变,通过检测这个来回改变的次数,可以计算出步数。

在游戏里能通过加速度传感器触发特殊指令。日常应用中的一些甩动切歌、翻转静音等也都用到了这枚传感器。

注意:
至于为什么不用线性加速传感器,是因为线性加速度传感器和加速度传感器在定义、工作原理以及应用场景上存在显著的区别。线性主要是来检测物体在直线方向上的位移。

二、功能开发思路:

1.根据通过@ohos.sensor接口,获取加速度传感器的数值,添加权限:ohos.permission.ACCELEROMETER

dart 复制代码
 {
        "name": "ohos.permission.ACCELEROMETER",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      }
dart 复制代码
 sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {

      }, { interval: 100000000 }); // 设置间隔为100000000 ns  = 0.1 s

2.将x,y,z三个方向的数值进行绝对值处理,获取运动数值

dart 复制代码
 sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
       console.info(this.TAG, 'Succeeded in invoking on. X-coordinate component: ' + data.x);
        console.info(this.TAG,'Succeeded in invoking on. Y-coordinate component: ' + data.y);
        console.info(this.TAG,'Succeeded in invoking on. Z-coordinate component: ' + data.z);
      }, { interval: 100000000 }); // 设置间隔为100000000 ns  = 0.1 s

3.根据运动数值进行判断,是否符合摇一摇的运动区间

dart 复制代码
        let x = Math.abs(data.x);
        let y = Math.abs(data.y);
        let z  = Math.abs(data.z);

        this.message = "x : " + x + "  y: " +  y + " z: " + z;
        if(x > this.SWING_VAL || y > this.SWING_VAL || z > this.SWING_VAL){
          promptAction.showToast({
            message: "手机正在摇一摇!"
          })
        }

最后一步,当然就是使用手机设备进行代码功能效果的验证。

若没有真机设备,使用模拟器,点击该按钮可实现摇一摇手机的触发。

注意:
不使用加速传感器时,一定要移除监听。否则会白白损耗性能。

三、源码示例:

dart 复制代码
import { sensor } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
struct SensorTestPage {

  private TAG: string = "SenorTestPage";
  private SWING_VAL: number = 50;

  @State message: string = '';

  aboutToAppear(): void {
    try {
      // 订阅加速度传感器返回的数据
      sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {

        console.info(this.TAG, 'Succeeded in invoking on. X-coordinate component: ' + data.x);
        console.info(this.TAG,'Succeeded in invoking on. Y-coordinate component: ' + data.y);
        console.info(this.TAG,'Succeeded in invoking on. Z-coordinate component: ' + data.z);

        let x = Math.abs(data.x);
        let y = Math.abs(data.y);
        let z  = Math.abs(data.z);

        this.message = "x : " + x + "  y: " +  y + " z: " + z;
        if(x > this.SWING_VAL || y > this.SWING_VAL || z > this.SWING_VAL){
          promptAction.showToast({
            message: "手机正在摇一摇!"
          })
        }

      }, { interval: 100000000 }); // 设置间隔为100000000 ns  = 0.1 s

    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(this.TAG, `Failed to invoke on. Code: ${e.code}, message: ${e.message}`);
    }
  }

  aboutToDisappear(): void {
    sensor.off(sensor.SensorId.ACCELEROMETER);
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('SenorTestPageHelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}

注意:
记得添加ohos.permission.ACCELEROMETER权限,否则无法监听到加速传感器!

相关推荐
亚历克斯神5 小时前
Flutter for OpenHarmony: Flutter 三方库 mutex 为鸿蒙异步任务提供可靠的临界资源互斥锁(并发安全基石)
android·数据库·安全·flutter·华为·harmonyos
钛态5 小时前
Flutter 三方库 smartstruct 鸿蒙化字段映射适配指南:介入静态预编译引擎扫除视图及数据模型双向强转类型错乱隐患,筑稳如磐石的企业级模型治理防线-适配鸿蒙 HarmonyOS ohos
flutter·华为·harmonyos
键盘鼓手苏苏5 小时前
Flutter 组件 csv2json 适配鸿蒙 HarmonyOS 实战:高性能异构数据转换,构建 CSV 流式解析与全栈式数据映射架构
flutter·harmonyos·鸿蒙·openharmony
雷帝木木5 小时前
Flutter 三方库 hrk_logging 的鸿蒙化适配指南 - 实现标准化分层日志记录、支持多目的地输出与日志分级过滤
flutter·harmonyos·鸿蒙·openharmony·hrk_logging
左手厨刀右手茼蒿5 小时前
Flutter 三方库 dio_compatibility_layer 的鸿蒙化适配指南 - 实现 Dio 跨主版本的平滑迁移、支持遗留拦截器兼容与网络请求架构稳定升级
flutter·harmonyos·鸿蒙·openharmony·dio_compatibility_layer
摘星编程5 小时前
开源力量:GitCode+昇腾NPU 部署Mistral-7B-Instruct-v0.2模型的技术探索与经验总结
华为·开源·huggingface·gitcode·昇腾
雷帝木木5 小时前
Flutter 三方库 hashids2 基于鸿蒙安全内核的深度隐匿映射适配:数字指纹泄露防御层、生成短小精悍唯一不可逆加盐哈希,护航全链路请求 URL 隐私-适配鸿蒙 HarmonyOS ohos
安全·flutter·harmonyos
HwJack207 小时前
HarmonyOS响应式布局与窗口监听:让界面像呼吸般灵动的艺术
ubuntu·华为·harmonyos
王码码20358 小时前
Flutter 组件 inappwebview_cookie_manager 适配 鸿蒙Harmony 实战 - 驾驭核心大 Web 容器缓存隧道、构建金融级政企应用绝对防串号跨域大隔离基座
flutter·harmonyos·鸿蒙·openharmony·inappwebview_cookie_manager
左手厨刀右手茼蒿8 小时前
Flutter 组件 ews 的适配 鸿蒙Harmony 实战 - 驾驭企业级 Exchange Web Services 协议、实现鸿蒙端政企办公同步与高安通讯隔离方案
flutter·harmonyos·鸿蒙·openharmony