HarmonyOS APP<<古今职鉴定>>开源教程第12篇:握姿感应:MultimodalAwarenessKit - on(&#39

📅 2026-11-30 👤 拼多多助力营销技巧 📂 首码项目 👁️ 185 次阅读

本篇学习鸿蒙独有的握姿感应能力,实现左手来财、右手来福

图:古今职鉴开源教程封面。本篇围绕「握姿感应:MultimodalAwarenessKit」展开。

学习目标

完成本篇后,你将能够:

✅ 理解多模态感知服务✅ 实现握持手检测✅ 处理权限申请✅ 处理设备兼容性

预计学习时间

约 90 分钟

---

实战一:理解多模态感知

第一步:什么是多模态感知

多模态感知(MultimodalAwarenessKit)是鸿蒙独有的能力,可以感知:

握持手状态(左手/右手)设备姿态环境光线其他传感器数据

第二步:握持手检测原理

系统通过以下方式判断握持手:

触摸屏边缘的接触点陀螺仪数据加速度计数据

第三步:应用场景

单手操作优化左右手不同功能游戏控制适配

---

实战二:配置权限

第一步:在 module.json5 中声明权限

{

"module": {

"requestPermissions": [

{

"name": "ohos.permission.DETECT_GESTURE",

"reason": "$string:gesture_permission_reason",

"usedScene": {

"abilities": ["EntryAbility"],

"when": "inuse"

}

}

]

}

}

第二步:添加权限说明字符串

在 resources/base/element/string.json 中添加:

{

"string": [

{

"name": "gesture_permission_reason",

"value": "用于检测握持手状态,提供更好的交互体验"

}

]

}

第三步:理解权限类型

权限类型说明DETECT_GESTUREuser_grant需要用户授权

---

实战三:实现握持手检测

第一步:导入模块

import { motion } from '@kit.MultimodalAwarenessKit';

import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit';

第二步:检查权限

async checkPermission(): Promise{

const permission: Permissions = 'ohos.permission.DETECT_GESTURE';

const bundleInfo = await bundleManager.getBundleInfoForSelf(

bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION

);

const tokenId = bundleInfo.appInfo.accessTokenId;

const atManager = abilityAccessCtrl.createAtManager();

const grantStatus = atManager.checkAccessTokenSync(tokenId, permission);

return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;

}

第三步:申请权限

async requestPermission(): Promise{

const permission: Permissions = 'ohos.permission.DETECT_GESTURE';

const atManager = abilityAccessCtrl.createAtManager();

try {

const result = await atManager.requestPermissionsFromUser(

getContext(this),

[permission]

);

return result.authResults[0] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;

} catch (error) {

console.error('请求权限失败:', error);

return false;

}

}

第四步:监听握持手变化

@Entry

@Component

struct Lesson12Page {

@State holdingHand: string = '未知';

@State hasPermission: boolean = false;

@State isSupported: boolean = true;

@State errorMessage: string = '';

async aboutToAppear() {

await this.initHoldingHandDetection();

}

aboutToDisappear() {

this.stopHoldingHandDetection();

}

async initHoldingHandDetection() {

// 检查权限

this.hasPermission = await this.checkPermission();

if (!this.hasPermission) {

this.hasPermission = await this.requestPermission();

}

if (!this.hasPermission) {

this.errorMessage = '未获得手势检测权限';

return;

}

// 开始监听

this.startHoldingHandDetection();

}

startHoldingHandDetection() {

try {

motion.on('holdingHandChanged', (data: motion.HoldingHandResponse) => {

switch (data.holdingHandStatus) {

case motion.HoldingHandStatus.LEFT_HAND:

this.holdingHand = '左手';

break;

case motion.HoldingHandStatus.RIGHT_HAND:

this.holdingHand = '右手';

break;

default:

this.holdingHand = '未知';

}

});

} catch (error) {

const err = error as BusinessError;

if (err.code === 801) {

this.isSupported = false;

this.errorMessage = '当前设备不支持握持手检测';

} else if (err.code === 201) {

this.hasPermission = false;

this.errorMessage = '权限未授权';

} else {

this.errorMessage = `错误: ${err.message}`;

}

}

}

stopHoldingHandDetection() {

try {

motion.off('holdingHandChanged');

} catch (error) {

// 忽略错误

}

}

}

第五步:处理错误码

错误码说明处理方式201权限未授权引导用户授权801设备不支持显示提示,优雅降级

---

实战四:实现左手来财、右手来福

第一步:设计界面

import { motion } from '@kit.MultimodalAwarenessKit';

import { abilityAccessCtrl, bundleManager, Permissions, common } from '@kit.AbilityKit';

import { BusinessError } from '@kit.BasicServicesKit';

@Entry

@Component

struct Lesson12Page {

@State holdingHand: string = '未知';

@State hasPermission: boolean = false;

@State isSupported: boolean = true;

@State blessing: string = '握住手机试试';

@State blessingIcon: Resource = $r('app.media.ic_pan_tool');

build() {

Column() {

// 头部

Row() {

Text('握姿感应')

.fontSize(18)

.fontWeight(FontWeight.Bold)

.fontColor('#1e293b')

}

.width('100%')

.height(56)

.padding({ left: 16, right: 16 })

.backgroundColor(Color.White)

// 内容

Column({ space: 30 }) {

if (!this.isSupported) {

this.UnsupportedView()

} else if (!this.hasPermission) {

this.NoPermissionView()

} else {

this.BlessingView()

}

}

.width('100%')

.layoutWeight(1)

.justifyContent(FlexAlign.Center)

.padding(20)

}

.width('100%')

.height('100%')

.backgroundColor('#f8f6f5')

}

@Builder

BlessingView() {

Column({ space: 20 }) {

// 祝福图标

Image(this.blessingIcon)

.width(120)

.height(120)

.fillColor(this.holdingHand === '左手' ? '#fbbf24' : '#c41e3a')

// 握持状态

Text(`当前握持: ${this.holdingHand}`)

.fontSize(16)

.fontColor('#64748b')

// 祝福语

Text(this.blessing)

.fontSize(28)

.fontWeight(FontWeight.Bold)

.fontColor(this.holdingHand === '左手' ? '#fbbf24' : '#c41e3a')

// 提示

Text('切换左右手握持,获得不同祝福')

.fontSize(14)

.fontColor('#9ca3af')

.margin({ top: 40 })

}

}

@Builder

UnsupportedView() {

Column({ space: 16 }) {

Image($r('app.media.ic_warning'))

.width(64)

.height(64)

.fillColor('#f59e0b')

Text('设备不支持')

.fontSize(18)

.fontColor('#1e293b')

Text('当前设备不支持握持手检测功能')

.fontSize(14)

.fontColor('#64748b')

}

}

@Builder

NoPermissionView() {

Column({ space: 16 }) {

Image($r('app.media.ic_lock'))

.width(64)

.height(64)

.fillColor('#64748b')

Text('需要权限')

.fontSize(18)

.fontColor('#1e293b')

Text('请授予手势检测权限以使用此功能')

.fontSize(14)

.fontColor('#64748b')

Button('授予权限')

.onClick(async () => {

this.hasPermission = await this.requestPermission();

if (this.hasPermission) {

this.startHoldingHandDetection();

}

})

.backgroundColor('#c41e3a')

.margin({ top: 20 })

}

}

}

第二步:根据握持手更新祝福

startHoldingHandDetection() {

try {

motion.on('holdingHandChanged', (data: motion.HoldingHandResponse) => {

switch (data.holdingHandStatus) {

case motion.HoldingHandStatus.LEFT_HAND:

this.holdingHand = '左手';

this.blessing = ' 左手来财';

this.blessingIcon = $r('app.media.ic_paid');

break;

case motion.HoldingHandStatus.RIGHT_HAND:

this.holdingHand = '右手';

this.blessing = '裏 右手来福';

this.blessingIcon = $r('app.media.ic_celebration');

break;

default:

this.holdingHand = '未知';

this.blessing = '握住手机试试';

this.blessingIcon = $r('app.media.ic_pan_tool');

}

});

} catch (error) {

this.handleError(error as BusinessError);

}

}

第三步:运行验证

hvigorw assembleHap --no-daemon

预期效果:

左手握持显示"左手来财"右手握持显示"右手来福"设备不支持时显示提示

---

实战五:封装权限工具类

第一步:创建 PermissionUtil

// PermissionUtil.ets

import { abilityAccessCtrl, bundleManager, Permissions, common } from '@kit.AbilityKit';

export class PermissionUtil {

static async check(permission: Permissions): Promise{

try {

const bundleInfo = await bundleManager.getBundleInfoForSelf(

bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION

);

const tokenId = bundleInfo.appInfo.accessTokenId;

const atManager = abilityAccessCtrl.createAtManager();

const grantStatus = atManager.checkAccessTokenSync(tokenId, permission);

return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;

} catch {

return false;

}

}

static async request(

context: common.UIAbilityContext,

permissions: Permissions[]

): Promise{

try {

const atManager = abilityAccessCtrl.createAtManager();

const result = await atManager.requestPermissionsFromUser(context, permissions);

return result.authResults.every(

status => status === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED

);

} catch {

return false;

}

}

static async openSettings(context: common.UIAbilityContext): Promise{

const want: Want = {

bundleName: 'com.huawei.hmos.settings',

abilityName: 'com.huawei.hmos.settings.MainAbility',

uri: 'application_info_entry',

parameters: {

pushParams: context.abilityInfo.bundleName

}

};

await context.startAbility(want);

}

}

第二步:使用工具类

async initHoldingHandDetection() {

const permission: Permissions = 'ohos.permission.DETECT_GESTURE';

this.hasPermission = await PermissionUtil.check(permission);

if (!this.hasPermission) {

const context = getContext(this) as common.UIAbilityContext;

this.hasPermission = await PermissionUtil.request(context, [permission]);

}

if (this.hasPermission) {

this.startHoldingHandDetection();

}

}

---

完整代码

// 文件路径:products/jiaocheng/src/main/ets/lesson12/Lesson12Page.ets

import { motion } from '@kit.MultimodalAwarenessKit';

import { abilityAccessCtrl, bundleManager, Permissions, common } from '@kit.AbilityKit';

import { BusinessError } from '@kit.BasicServicesKit';

@Entry

@Component

struct Lesson12Page {

@State holdingHand: string = '未知';

@State hasPermission: boolean = false;

@State isSupported: boolean = true;

@State blessing: string = '握住手机试试';

@State blessingColor: string = '#64748b';

async aboutToAppear() {

await this.initHoldingHandDetection();

}

aboutToDisappear() {

this.stopHoldingHandDetection();

}

async checkPermission(): Promise{

try {

const permission: Permissions = 'ohos.permission.DETECT_GESTURE';

const bundleInfo = await bundleManager.getBundleInfoForSelf(

bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION

);

const tokenId = bundleInfo.appInfo.accessTokenId;

const atManager = abilityAccessCtrl.createAtManager();

const grantStatus = atManager.checkAccessTokenSync(tokenId, permission);

return grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;

} catch {

return false;

}

}

async requestPermission(): Promise{

try {

const permission: Permissions = 'ohos.permission.DETECT_GESTURE';

const atManager = abilityAccessCtrl.createAtManager();

const context = getContext(this) as common.UIAbilityContext;

const result = await atManager.requestPermissionsFromUser(context, [permission]);

return result.authResults[0] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED;

} catch {

return false;

}

}

async initHoldingHandDetection() {

this.hasPermission = await this.checkPermission();

if (!this.hasPermission) {

this.hasPermission = await this.requestPermission();

}

if (this.hasPermission) {

this.startHoldingHandDetection();

}

}

startHoldingHandDetection() {

try {

motion.on('holdingHandChanged', (data: motion.HoldingHandResponse) => {

switch (data.holdingHandStatus) {

case motion.HoldingHandStatus.LEFT_HAND:

this.holdingHand = '左手';

this.blessing = ' 左手来财';

this.blessingColor = '#fbbf24';

break;

case motion.HoldingHandStatus.RIGHT_HAND:

this.holdingHand = '右手';

this.blessing = '裏 右手来福';

this.blessingColor = '#c41e3a';

break;

default:

this.holdingHand = '未知';

this.blessing = '握住手机试试';

this.blessingColor = '#64748b';

}

});

} catch (error) {

const err = error as BusinessError;

if (err.code === 801) {

this.isSupported = false;

}

}

}

stopHoldingHandDetection() {

try {

motion.off('holdingHandChanged');

} catch {

// 忽略

}

}

build() {

Column() {

Row() {

Text('握姿感应')

.fontSize(18)

.fontWeight(FontWeight.Bold)

.fontColor('#1e293b')

}

.width('100%')

.height(56)

.padding({ left: 16, right: 16 })

.backgroundColor(Color.White)

Column({ space: 30 }) {

if (!this.isSupported) {

Column({ space: 16 }) {

Image($r('app.media.ic_warning'))

.width(64)

.height(64)

.fillColor('#f59e0b')

Text('设备不支持')

.fontSize(18)

.fontColor('#1e293b')

Text('当前设备不支持握持手检测功能')

.fontSize(14)

.fontColor('#64748b')

}

} else if (!this.hasPermission) {

Column({ space: 16 }) {

Image($r('app.media.ic_lock'))

.width(64)

.height(64)

.fillColor('#64748b')

Text('需要权限')

.fontSize(18)

.fontColor('#1e293b')

Button('授予权限')

.onClick(async () => {

this.hasPermission = await this.requestPermission();

if (this.hasPermission) {

this.startHoldingHandDetection();

}

})

.backgroundColor('#c41e3a')

}

} else {

Column({ space: 20 }) {

Text(`当前握持: ${this.holdingHand}`)

.fontSize(16)

.fontColor('#64748b')

Text(this.blessing)

.fontSize(32)

.fontWeight(FontWeight.Bold)

.fontColor(this.blessingColor)

Text('切换左右手握持,获得不同祝福')

.fontSize(14)

.fontColor('#9ca3af')

.margin({ top: 40 })

}

}

}

.width('100%')

.layoutWeight(1)

.justifyContent(FlexAlign.Center)

}

.width('100%')

.height('100%')

.backgroundColor('#f8f6f5')

} 拼多多帮助力入口

}

@Builder

export function Lesson12PageBuilder() {

Lesson12Page()

}

---

本课小结

核心知识点

知识点说明MultimodalAwarenessKit多模态感知服务motion.on监听握持手变化HoldingHandStatusLEFT_HAND / RIGHT_HAND错误码 801设备不支持错误码 201权限未授权

权限申请流程

在 module.json5 声明权限检查权限状态申请权限处理授权结果

---

课后练习

练习1:添加动画效果

切换握持手时添加过渡动画。

练习2:实现侧边栏滑出

左手握持时从左侧滑出菜单,右手握持时从右侧滑出。

---

下一课预告

第13课我们将学习隔空投送,包括:

ShareKit 能力介绍隔空传送手势监听分享数据构建分享流程与回调

项目开源地址

https://gitcode.com/daleishen/gujinzhijian,HarmonyOS

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧