• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 按键拦截监听开发指导
2
3## 场景介绍
4
5按键拦截监听支持应用在前台状态下监听物理按键的按下事件,当前按键仅支持音量加和音量减。该接口不仅可以订阅用户按键行为,还可屏蔽按键的系统默认响应,如音量调节。
6
7使用场景例如:开发者可在阅读类应用中监听音量键实现翻页,或在相机类应用中监听音量键实现拍照功能,从而提升用户体验。当前仅支持手机和平板设备。
8
9## 导入模块
10
11```js
12import { inputConsumer, KeyEvent } from '@kit.InputKit';
13```
14
15## 接口说明
16
17按键按下事件常用接口如下表所示,接口详细介绍请参考[ohos.multimodalInput.inputConsumer文档](../../reference/apis-input-kit/js-apis-inputconsumer.md)。
18
19| 接口名称  | 描述 |
20| ------------------------------------------------------------ | -------------------------- |
21| on(type: "keyPressed", options: KeyPressedConfig, callback: Callback\<KeyEvent>): void |订阅指定按键按下事件,拦截系统默认响应。  |
22| off(type: "keyPressed", callback?: Callback\<KeyEvent>): void |取消按键事件订阅,恢复系统默认响应。  |
23
24## 开发步骤
25
26应用开启时调用[on](../../reference/apis-input-kit/js-apis-inputconsumer.md#inputconsumeronkeypressed16)方法订阅按键按下事件,应用关闭时再用[off](../../reference/apis-input-kit/js-apis-inputconsumer.md#inputconsumeroffkeypressed16)方法取消订阅按键按下事件。
27
28### 音量键翻页和应用内拍照
29
30在电子书或新闻阅读应用中,用户希望通过音量键控制翻页(例如:音量加键向下翻页,音量减键向上翻页);在相机或扫码类应用中,用户按音量键可直接拍照,而不跳转系统相机应用。
31
32```js
33import { inputConsumer, KeyEvent } from '@kit.InputKit';
34import { KeyCode } from '@kit.InputKit';
35
36@Entry
37@Component
38struct TestDemo14 {
39  private volumeUpCallBackFunc: (event: KeyEvent) => void = () => {
40  }
41  private volumeDownCallBackFunc: (event: KeyEvent) => void = () => {
42  }
43
44  aboutToAppear(): void {
45    try {
46      let options1: inputConsumer.KeyPressedConfig = {
47        key: KeyCode.KEYCODE_VOLUME_UP,
48        action: 1, // 按下按键的行为
49        isRepeat: false, // 优先消费掉按键事件,不上报
50      }
51      let options2: inputConsumer.KeyPressedConfig = {
52        key: KeyCode.KEYCODE_VOLUME_DOWN,
53        action: 1, // 按下按键的行为
54        isRepeat: false, // 优先消费掉按键事件,不上报
55      }
56
57      // 点击了音量按键上事件回调
58      this.volumeUpCallBackFunc = (event: KeyEvent) => {
59        this.getUIContext().getPromptAction().showToast({ message: '点击了音量按键上' })
60        // do something
61      }
62
63      // 点击了音量按键下事件回调
64      this.volumeDownCallBackFunc = (event: KeyEvent) => {
65        this.getUIContext().getPromptAction().showToast({ message: '点击了音量按键下' })
66        // do something
67      }
68      // 注册监听事件
69      inputConsumer.on('keyPressed', options1, this.volumeUpCallBackFunc);
70      inputConsumer.on('keyPressed', options2, this.volumeDownCallBackFunc);
71    } catch (error) {
72      console.error(`Subscribe execute failed, error: ${JSON.stringify(error, ["code", "message"])}`);
73    }
74  }
75
76  build() {
77    Column() {
78      Row() {
79        Button('取消监听音量按键上的监听')
80          .onClick(() => {
81            try {
82              // 取消指定回调函数
83              inputConsumer.off('keyPressed', this.volumeUpCallBackFunc);
84              this.getUIContext().getPromptAction().showToast({ message: '取消监听音量按键上的监听事件成功!' })
85            } catch (error) {
86              console.error(`Unsubscribe execute failed, error: ${JSON.stringify(error, ["code", "message"])}`);
87            }
88          })
89      }.width('100%')
90      .justifyContent(FlexAlign.Center)
91      .margin({ top: 20, bottom: 50 })
92
93      Row() {
94        Button('取消监听音量按键下的监听')
95          .onClick(() => {
96            try {
97              // 取消指定回调函数
98              inputConsumer.off('keyPressed', this.volumeDownCallBackFunc);
99              this.getUIContext().getPromptAction().showToast({ message: '取消监听音量按键下的监听事件成功!' })
100            } catch (error) {
101              console.error(`Unsubscribe execute failed, error: ${JSON.stringify(error, ["code", "message"])}`);
102            }
103          })
104      }.width('100%')
105      .justifyContent(FlexAlign.Center)
106      .margin({ top: 20, bottom: 50 })
107      Row(){
108        Text('已默认添加监听音量按键上和下的监听')
109      }
110      .width('100%')
111      .justifyContent(FlexAlign.Center)
112    }.width('100%').height('100%')
113  }
114}
115```
116