HarmonyOS 监听音量键动作?

onKeyEvent回调有限制吗,我在demo上试了下只能在build的顶层组件注册才能收到监听,注释处Button注册是收不到的。而在工程上就都收不到回调了,或者有没其他方案可以监听音量键动作

相关代码;

build() {
  Stack() {
    Button('KeyEvent')
    // .onKeyPreIme((event) => {
    //   console.log(`onKeyPreIme ${JSON.stringify(event)}`);
    //   return true
    // })
  }
  .onKeyPreIme((event) => {
    console.log(`onKeyPreIme ${JSON.stringify(event)}`);
    return true;
  })
}
阅读 570
1 个回答

onKeyEvent回调 依赖绑定组件是否获焦,参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-events-key-V5

可以监听音量变化来实现监听音量键动作

import audio from '@ohos.multimedia.audio';
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  aboutToAppear() {
    let audioVolumeManager = audio.getAudioManager().getVolumeManager().on('volumeChange', (volumeEvent: audio.VolumeEvent) => {
      console.info(`tag VolumeType of stream: ${volumeEvent.volumeType} `);
      console.info(`tagVolume level: ${volumeEvent.volume} `);
      console.info(`tag Whether to updateUI: ${volumeEvent.updateUi} `);
    });
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进