• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Key Press Event Listening Development
2
3## When to Use
4
5Key press event listening allows an application to listen for physical key press events when running in the foreground. Currently, this function applies only to the volume up and volume down keys. It enables applications to subscribe to key press events and override default system responses to those events, such as volume adjustments.
6
7You can enhance user experience by leveraging volume key listeners to implement context-specific actions, such as binding page-turning functionality in reading apps or triggering the camera shutter in photography apps. Currently, this function is available only for mobile phones and tablets.
8
9## Modules to Import
10
11```js
12import { inputConsumer, KeyEvent } from '@kit.InputKit';
13```
14
15## Available APIs
16
17The following table lists the APIs related to key press event listening. For details about the APIs, see [ohos.multimodalInput.inputConsumer](../../reference/apis-input-kit/js-apis-inputconsumer.md).
18
19| API | Description|
20| ------------------------------------------------------------ | -------------------------- |
21| on(type: "keyPressed", options: KeyPressedConfig, callback: Callback\<KeyEvent>): void |Subscribes to press events of the specified key and intercepts the default system response. |
22| off(type: "keyPressed", callback?: Callback\<KeyEvent>): void |Unsubscribes from press events of the specified key and restores the default system response. |
23
24## How to Develop
25
26When an application is started, call [on](../../reference/apis-input-kit/js-apis-inputconsumer.md#inputconsumeronkeypressed16) to subscribe to key press events. When the application is closed, call [off](../../reference/apis-input-kit/js-apis-inputconsumer.md#inputconsumeroffkeypressed16) to unsubscribe from key press events.
27
28### Page Turning and In-App Photographing via the Volume Button
29
30In e-book or news reading apps, users can navigate pages via volume buttons—typically, the volume-up button turns to the next page, while the volume-down button returns to the previous page. In camera or barcode scanning apps, pressing a volume button triggers instant photography without switching to the system's camera interface.
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, // The value 1 indicates a key press.
49        isRepeat: false, // Key events are consumed preferentially and not reported.
50      }
51      let options2: inputConsumer.KeyPressedConfig = {
52        key: KeyCode.KEYCODE_VOLUME_DOWN,
53        action: 1, // The value 1 indicates a key press.
54        isRepeat: false, // Key events are consumed preferentially and not reported.
55      }
56
57      // Callback invoked when the Volume Up button is pressed
58      this.volumeUpCallBackFunc = (event: KeyEvent) => {
59        this.getUIContext().getPromptAction().showToast({ message: 'The Volume Up button was pressed.' });
60        // do something
61      }
62
63      // Callback invoked when the Volume Down button is pressed
64      this.volumeDownCallBackFunc = (event: KeyEvent) => {
65        this.getUIContext().getPromptAction().showToast({ message: 'The Volume Down button was pressed.' });
66        // do something
67      }
68      // Register an event listener.
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 ('Cancel listening for Volume Up button events')
80          .onClick(() => {
81            try {
82              // Disable listening for a single callback.
83              inputConsumer.off('keyPressed', this.volumeUpCallBackFunc);
84              this.getUIContext().getPromptAction().showToast({ message: ''Listening for Volume Up button events is canceled successfully.' });
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 ('Cancel listening for Volume Down button events')
95          .onClick(() => {
96            try {
97              // Disable listening for a single callback.
98              inputConsumer.off('keyPressed', this.volumeDownCallBackFunc);
99              this.getUIContext().getPromptAction().showToast({ message: 'Listening for Volume Down button events is canceled successfully.' });
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 ('Listening is enabled for Volume Down and Volume Down button events by default.')
109      }
110      .width('100%')
111      .justifyContent(FlexAlign.Center)
112    }.width('100%').height('100%')
113  }
114}
115```
116