• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16// [Start taskpool_listen_sensor_data]
17import { sensor } from '@kit.SensorServiceKit';
18import { taskpool } from '@kit.ArkTS';
19import { BusinessError, emitter } from '@kit.BasicServicesKit';
20
21@Concurrent
22async function sensorListener(): Promise<void> {
23  sensor.on(sensor.SensorId.ACCELEROMETER, (data) => {
24    emitter.emit({ eventId: 0 }, { data: data });
25  }, { interval: 1000000000 });
26
27  emitter.on({ eventId: 1 }, () => {
28    sensor.off(sensor.SensorId.ACCELEROMETER)
29    emitter.off(1)
30  })
31}
32
33@Entry
34@Component
35struct Index {
36  sensorTask?: taskpool.LongTask
37  @State addListener: string = 'Add listener';
38  @State deleteListener: string = 'Delete listener';
39
40  build() {
41    Column() {
42      Text(this.addListener)
43        .id('Add listener')
44        .fontSize(50)
45        .fontWeight(FontWeight.Bold)
46        .onClick(() => {
47          this.sensorTask = new taskpool.LongTask(sensorListener);
48          emitter.on({ eventId: 0 }, (data) => {
49            // Do something here
50            console.info(`Receive ACCELEROMETER data: {${data.data?.x}, ${data.data?.y}, ${data.data?.z}`);
51          });
52          taskpool.execute(this.sensorTask).then(() => {
53            console.info('Add listener of ACCELEROMETER success');
54          }).catch((e: BusinessError) => {
55            // Process error
56          })
57          this.addListener = 'success';
58        })
59      Text(this.deleteListener)
60        .id('Delete listener')
61        .fontSize(50)
62        .fontWeight(FontWeight.Bold)
63        .onClick(() => {
64          emitter.emit({ eventId: 1 });
65          emitter.off(0);
66          if (this.sensorTask != undefined) {
67            taskpool.terminateTask(this.sensorTask);
68          } else {
69            console.error('sensorTask is undefined.');
70          }
71          this.deleteListener = 'success';
72        })
73    }
74    .height('100%')
75    .width('100%')
76  }
77}
78// [End taskpool_listen_sensor_data]