鸿蒙中传感器判断移动

1、权限

TypeScript 复制代码
     {
        "name": "ohos.permission.ACCELEROMETER",
        "reason": "$string:accelerometer_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "inuse"
        }
      },
      {
        "name": "ohos.permission.GYROSCOPE",
        "reason": "$string:gyroscope_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "inuse"
        }
      },
      {
        "name": "ohos.permission.ACTIVITY_MOTION",
        "reason": "$string:activity_motion_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "inuse"
        }

2、使用

TypeScript 复制代码
import { sensor } from '@kit.SensorServiceKit';
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  @State isWalking: boolean = false;
  @State hasPermission: boolean = false;
  private context = getContext(this) as common.UIAbilityContext;

  async aboutToAppear(): Promise<void> {
    await this.requestPermission();
  }

  async requestPermission(): Promise<void> {
    const atManager = abilityAccessCtrl.createAtManager();
    const permission: Permissions = 'ohos.permission.ACTIVITY_MOTION';

    const grantStatus = await atManager.checkAccessToken(
      this.context.applicationInfo.accessTokenId,
      permission
    );

    if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      this.hasPermission = true;
      return;
    }

    const result = await atManager.requestPermissionsFromUser(this.context, [permission]);
    this.hasPermission = result.authResults[0] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;
  }

  onPageShow(): void {
    if (!this.hasPermission) {
      return;
    }

    sensor.on(sensor.SensorId.PEDOMETER_DETECTION, (data: sensor.PedometerDetectionResponse) => {
      this.isWalking = data.scalar === 1;
      console.log(this.isWalking ? ' 正在行走' : ' 停止行走');
    });
  }

  onPageHide(): void {
    sensor.off(sensor.SensorId.PEDOMETER_DETECTION);
  }

  build() {
    Column({ space: 20 }) {
      if (!this.hasPermission) {
        Text(' 需要运动检测权限')
        Button('授权').onClick(async () => {
          await this.requestPermission();
          if (this.hasPermission) {
            this.onPageShow();
          }
        })
      } else {
        Text(this.isWalking ? ' 正在行走' : ' 静止中')
          .fontSize(30)
          .fontColor(this.isWalking ? Color.Green : Color.Gray)
      }
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
相关推荐
智塑未来15 小时前
鸿蒙游戏体验手册:四种能力从性能到玩法逐一解锁
游戏·华为·harmonyos
math_hongfan16 小时前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙
math_hongfan19 小时前
鸿蒙企业级数据存储高级架构:从读写分离到冷热数据分层/归档策略/数据生命周期管理最佳实践
人工智能·学习·华为·架构·harmonyos·鸿蒙
math_hongfan1 天前
鸿蒙存储异常高级排查:文件损坏检测/数据恢复/读写失败重试/磁盘空间预警系统性根治方案
学习·华为·harmonyos·鸿蒙
lilian2331 天前
Harmony os 技术实战|拼豆制图10:把取消、解析失败和保存失败写成可恢复状态机
java·javascript·华为·harmonyos
2501_919749031 天前
华为鸿蒙美缝剂实用APP—小羊美缝
华为·harmonyos
2501_919749031 天前
华为鸿蒙积攒年度高光APP—小羊高光
华为·harmonyos
智塑未来1 天前
鸿蒙7碰一碰智感交互——碰哪儿传哪儿
华为·harmonyos
math_hongfan1 天前
鸿蒙存储碎片高级清理机制:数据库Vacuum/文件碎片整理/缓存过期清理/主动空间回收策略
jvm·数据库·学习·缓存·华为·harmonyos·鸿蒙
梦想不只是梦与想1 天前
鸿蒙UI测试框架:UITest
harmonyos·uitest·ui测试框架