• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using Motion and Orientation Sensors
2
3## Overview
4
5The motion and orientation sensors, such as an accelerometer and a gyroscope, can monitor the motion status and orientation change (such as rotation and tilt) of the device.
6Through the W3C standards-compliant API, the **Web** component can access the sensor data to implement richer user interaction features. For example, in a web application, you can use an accelerometer to identify the motion mode and instruct the user to exercise, and use a gyroscope to capture the tilt and rotation of the device in the hand of the player, implementing game experience without button control.
7
8To access the motion and orientation sensors, invoke the following W3C standards-compliant APIs in JavaScript:
9
10| API                     | Name        | Description                                                                                                                                                    |
11| ------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
12| Accelerometer             | Accelerometer      | Obtains acceleration data in the X, Y, and Z axes.                                                                                                                   |
13| Gyroscope                 | Gyroscope      | Obtains angular velocity data in the X, Y, and Z axes.                                                                                                                   |
14| AbsoluteOrientationSensor | Absolute orientation    | Obtains the quaternion including the X, Y, Z, and W components that indicates the absolute orientation of the device.                                                                                                |
15| RelativeOrientationSensor | Relative orientation    | Obtains the quaternion including the X, Y, Z, and W components that indicates the relative orientation of the device.                                                                                                |
16| DeviceMotionEvent         | Device motion event| Listens for the device motion events to obtain the acceleration data of the device in the X, Y, and Z axes, acceleration data that contains gravity in the X, Y, and Z axes, and rotation rate data of the device in the alpha, beta, and gamma axes.|
17| DeviceOrientationEvent    | Device orientation event| Listens for the device orientation events to obtain the angles of the device around the X, Y, and Z axes.                                                                                                           |
18
19## Required Permission
20
21To use the preceding APIs, you need to declare the corresponding sensor permissions in the **module.json5** file. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
22
23```
24    "requestPermissions":[
25      {
26        "name": "ohos.permission.ACCELEROMETER" // Accelerometer permission
27      },
28      {
29        "name": "ohos.permission.GYROSCOPE"      // Gyroscope permission
30      }
31    ]
32```
33
34When the **Web** component is connected to a motion or orientation sensor, configure [onPermissionRequest](../reference/apis-arkweb/arkts-basic-components-web-events.md#onpermissionrequest9) to receive permission request notifications.
35
36## How to Develop
37
381. In the application code, configure [onPermissionRequest](../reference/apis-arkweb/arkts-basic-components-web-events.md#onpermissionrequest9) for the **Web** component and use the [getAccessibleResource](../reference/apis-arkweb/arkts-basic-components-web-PermissionRequest.md#getaccessibleresource9) API of [PermissionRequest](../reference/apis-arkweb/arkts-basic-components-web-PermissionRequest.md) to obtain the resource type of the request permission. When the resource type is **TYPE_SENSOR**, the sensor is authorized.
39
40   ```ts
41   import { webview } from '@kit.ArkWeb';
42   import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit';
43   import { BusinessError } from '@kit.BasicServicesKit';
44
45   @Entry
46   @Component
47   struct WebComponent {
48     controller: webview.WebviewController = new webview.WebviewController();
49     uiContext: UIContext = this.getUIContext();
50
51     aboutToAppear() {
52       // Enable web frontend page debugging.
53       webview.WebviewController.setWebDebuggingAccess(true);
54       // Create an **AtManager** instance, which is used for application access control.
55       let atManager = abilityAccessCtrl.createAtManager();
56       try {
57         atManager.requestPermissionsFromUser(this.uiContext.getHostContext(), ['ohos.permission.ACCELEROMETER', 'ohos.permission.GYROSCOPE']
58           , (err: BusinessError, data: PermissionRequestResult) => {
59           console.info('data permissions:' + data.permissions);
60           console.info('data authResults:' + data.authResults);
61         })
62       } catch (error) {
63         console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
64       }
65     }
66
67     build() {
68       Column() {
69         Web({ src: $rawfile('index.html'), controller: this.controller })
70           .onPermissionRequest((event) => {
71             if (event) {
72                this.uiContext.showAlertDialog({
73                 title: 'title',
74                 message: 'text',
75                 primaryButton: {
76                   value: 'deny',
77                   action: () => {
78                     event.request.deny();
79                   }
80                 },
81                 secondaryButton: {
82                   value: 'onConfirm',
83                   action: () => {
84                     event.request.grant(event.request.getAccessibleResource());
85                   }
86                 },
87                 autoCancel: false,
88                 cancel: () => {
89                   event.request.deny();
90                 }
91               })
92             }
93           })
94       }
95     }
96   }
97   ```
98
992. In the frontend page code, use JavaScript to call the W3C standards-compliant API related to the sensor.
100
101   ```html
102   <!DOCTYPE HTML>
103   <html>
104   <head>
105       <meta charset="utf-8" />
106       <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
107       <meta name="misapplication-tap-highlight" content="no" />
108       <meta name="HandheldFriendly" content="true" />
109       <meta name="MobileOptimized" content="320" />
110       <title>Motion and direction sensor</title>
111       <meta charset="UTF-8">
112       <style>
113           body {
114               font-family: Arial, sans-serif;
115           }
116       </style>
117       <script type="text/javascript">
118           // Access the accelerometer of the device and obtain its data.
119           function getAccelerometer() {
120               var acc = new Accelerometer({frequency: 60});
121               acc.addEventListener('activate', () => console.log('Ready to measure.'));
122               acc.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error ));
123               acc.addEventListener('reading', () => {
124                   console.log(`Accelerometer ${acc.timestamp}, ${acc.x}, ${acc.y}, ${acc.z}.`);
125               });
126               acc.start();
127           }
128
129           // Access the gyroscope of the device and obtain its data.
130           function getGyroscope() {
131               var gyr = new Gyroscope({frequency: 60});
132               gyr.addEventListener('activate', () => console.log('Ready to measure.'));
133               gyr.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error ));
134               gyr.addEventListener('reading', () => {
135                   console.log(`Gyroscope ${gyr.timestamp}, ${gyr.x}, ${gyr.y}, ${gyr.z}.`);
136               });
137               gyr.start();
138           }
139
140           // Access the orientation sensor of the device and obtain its data.
141           function getAbsoluteOrientationSensor() {
142               var aos = new AbsoluteOrientationSensor({frequency: 60});
143               aos.addEventListener('activate', () => console.log('Ready to measure.'));
144               aos.addEventListener('error', error => console.log('Error type: ' + error.type + ', error: ' + error.error ));
145               aos.addEventListener('reading', () => {
146                   console.log(`AbsoluteOrientationSensor data: ${aos.timestamp}, ${aos.quaternion}`);
147               });
148               aos.start();
149           }
150
151           // Listen for the motion events of the device and execute the corresponding processing logic.
152           function listenDeviceMotionEvent() {
153               removeDeviceMotionEvent();
154               if ('DeviceMotionEvent' in window) {
155                   window.addEventListener('devicemotion', handleMotionEvent, false);
156               } else {
157                 console.log ("DeviceMotionEvent is not supported.");
158               }
159           }
160
161           // Remove the device motion event listener.
162           function removeDeviceMotionEvent() {
163               if ('DeviceMotionEvent' in window) {
164                 window.removeEventListener('devicemotion', handleMotionEvent, false);
165               } else {
166                 console.log ("DeviceOrientationEvent is not supported.");
167               }
168           }
169
170           // Handle the motion event.
171           function handleMotionEvent(event) {
172               const x = event.accelerationIncludingGravity.x;
173               const y = event.accelerationIncludingGravity.y;
174               const z = event.accelerationIncludingGravity.z;
175               console.log(`DeviceMotionEvent data: ${event.timeStamp}, ${x}, ${y}, ${z}`);
176           }
177
178           // Listen for the device orientation events and execute the corresponding processing logic.
179           function listenDeviceOrientationEvent() {
180               removeDeviceOrientationEvent();
181               if ('DeviceOrientationEvent' in window) {
182                   window.addEventListener('deviceorientation', handleOrientationEvent, false);
183               } else {
184                   console.log ("DeviceOrientationEvent is not supported.");
185               }
186           }
187
188           // Remove the device orientation event listener.
189           function removeDeviceOrientationEvent() {
190               if ('DeviceOrientationEvent' in window) {
191                 window.removeEventListener('deviceorientation', handleOrientationEvent, false);
192               } else {
193                 console.log ("DeviceOrientationEvent is not supported.");
194               }
195           }
196
197           // Listen for the device orientation events and execute the corresponding processing logic.
198           function listenDeviceOrientationEvent2() {
199               removeDeviceOrientationEvent2();
200               if ('DeviceOrientationEvent' in window) {
201                   window.addEventListener('deviceorientationabsolute', handleOrientationEvent, false);
202               } else {
203                   console.log ("DeviceOrientationEvent is not supported.");
204               }
205           }
206
207           // Remove the device orientation event listener.
208           function removeDeviceOrientationEvent2() {
209               if ('DeviceOrientationEvent' in window) {
210                 window.removeEventListener('deviceorientationabsolute', handleOrientationEvent, false);
211               } else {
212                 console.log ("DeviceOrientationEvent is not supported.");
213               }
214           }
215
216           // Handle the orientation event.
217           function handleOrientationEvent(event) {
218               console.log(`DeviceOrientationEvent data: ${event.timeStamp}, ${event.absolute}, ${event.alpha}, ${event.beta}, ${event.gamma}`);
219           }
220       </script>
221   </head>
222   <body>
223   <div id="dcontent" class="dcontent">
224       <h3>Motion and orientation:</h3>
225       <ul class="dlist">
226           <li><button type="button" onclick="getAccelerometer()">Accelerometer</button></li>;
227           <li><button type="button" onclick="getGyroscope()">Gyroscope</button></li>
228           <li><button type="button" onclick="getAbsoluteOrientationSensor()">Device (absolute) orientation</button></li>;
229           <li><button type="button" onclick="listenDeviceMotionEvent()">Device motion event</button></li>;
230           <li><button type="button" onclick="listenDeviceOrientationEvent()">Device orientation event</button></li>;
231           <li><button type="button" onclick="listenDeviceOrientationEvent2()">Device (absolute) orientation event</button></li>;
232       </ul>
233   </div>
234   </body>
235   </html>
236   ```
237