往期鸿蒙全套实战精彩文章必看内容:
- 鸿蒙开发核心知识点,看这篇文章就够了
- 最新版!鸿蒙HarmonyOS Next应用开发实战学习路线
- 鸿蒙HarmonyOS NEXT开发技能最全学习路线指南
- 鸿蒙应用开发实战项目,看这一篇文章就够了(部门项目附源码)
利用运动和方向传感器
Web组件可以通过W3C尺度协议接口对接运动和方向相关的传感器。开发者在利用该功能中的加速率、陀螺仪及装备运动变乱接口时,需在设置文件中声明相应的传感器权限。
- 利用加速率和装备运动变乱接口前请在module.json5中添加加速率权限。
- "requestPermissions":[
- {
- "name" : "ohos.permission.ACCELEROMETER"
- }
- ]
复制代码 - 利用陀螺仪接口前请在module.json5中添加陀螺仪权限。
- "requestPermissions":[
- {
- "name" : "ohos.permission.GYROSCOPE"
- }
- ]
复制代码 Web组件在对接运动和方向传感器时,需设置onPermissionRequest接口,通过该接口接收权限请求通知。
通过在JavaScript中调用下面这些W3C尺度协议接口,可以访问运动和方向传感器。
接口名称是否支持阐明Accelerometer加速率支持-Gyroscope陀螺仪支持-AbsoluteOrientationSensor绝对定位支持-RelativeOrientationSensor相对定位不支持传感器数据暂不支持DeviceMotionEvent装备运动变乱支持-DeviceOrientationEvent装备方向变乱支持可获取绝对定位方向 RelativeOrientationSensor受限于利用到的传感器功能暂未设置,暂不支持利用该接口监听装备相对定位方向数据。
在下面的示例中,点击index.html前端页面各种按钮,监听相应数据。
- 应用侧代码。
- import { webview } from '@kit.ArkWeb';
- import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit';
- import { BusinessError } from '@kit.BasicServicesKit';
- @Entry
- @Component
- struct WebComponent {
- controller: webview.WebviewController = new webview.WebviewController()
- aboutToAppear() {
- // 配置Web开启调试模式
- webview.WebviewController.setWebDebuggingAccess(true);
- // 访问控制管理, 获取访问控制模块对象。
- let atManager = abilityAccessCtrl.createAtManager();
- try {
- atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.ACCELEROMETER', 'ohos.permission.GYROSCOPE']
- , (err: BusinessError, data: PermissionRequestResult) => {
- console.info('data:' + JSON.stringify(data));
- console.info('data permissions:' + data.permissions);
- console.info('data authResults:' + data.authResults);
- })
- } catch (error) {
- console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
- }
- }
- build() {
- Column() {
- Web({ src: $rawfile('index.html'), controller: this.controller })
- .onPermissionRequest((event) => {
- if (event) {
- AlertDialog.show({
- title: 'title',
- message: 'text',
- primaryButton: {
- value: 'deny',
- action: () => {
- event.request.deny();
- }
- },
- secondaryButton: {
- value: 'onConfirm',
- action: () => {
- event.request.grant(event.request.getAccessibleResource());
- }
- },
- autoCancel: false,
- cancel: () => {
- event.request.deny();
- }
- })
- }
- })
- }
- }
- }
复制代码 - 前端页面index.html代码。
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
- <meta name="misapplication-tap-highlight" content="no" />
- <meta name="HandheldFriendly" content="true" />
- <meta name="MobileOptimized" content="320" />
- <title>运动和方向传感器</title>
- <meta charset="UTF-8">
- <style>
- body {
- font-family: Arial, sans-serif;
- }
- </style>
- <script type="text/javascript">
- function getAccelerometer() {
- var acc = new Accelerometer({frequency: 60});
- acc.addEventListener('activate', () => console.log('Ready to measure.'));
- acc.addEventListener('error', error => console.log(`Error: ${error.name}`));
- acc.addEventListener('reading', () => {
- console.log(`[doc_sensor]Accelerometer ${acc.timestamp}, ${acc.x}, ${acc.y}, ${acc.z}.`);
- });
- acc.start();
- }
- function getGyroscope() {
- var gyr = new Gyroscope({frequency: 60});
- gyr.addEventListener('activate', () => console.log('Ready to measure.'));
- gyr.addEventListener('error', error => console.log(`Error: ${error.name}`));
- gyr.addEventListener('reading', () => {
- console.log(`[doc_sensor]Gyroscope ${gyr.timestamp}, ${gyr.x}, ${gyr.y}, ${gyr.z}.`);
- });
- gyr.start();
- }
- function getAbsoluteOrientationSensor() {
- var aos = new AbsoluteOrientationSensor({frequency: 60});
- aos.addEventListener('activate', () => console.log('Ready to measure.'));
- aos.addEventListener('error', error => console.log(`Error: ${error.name}`));
- aos.addEventListener('reading', () => {
- console.log(`AbsoluteOrientationSensor data: ${ros.timestamp}, ${ros.quaternion}`);
- });
- aos.start();
- }
- function listenDeviceMotionEvent() {
- removeDeviceMotionEvent();
- if ('DeviceMotionEvent' in window) {
- window.addEventListener('devicemotion', handleMotionEvent, false);
- } else {
- console.log('不支持DeviceMotionEvent');
- }
- }
- function removeDeviceMotionEvent() {
- if ('DeviceMotionEvent' in window) {
- window.removeEventListener('devicemotion', handleMotionEvent, false);
- } else {
- console.log('不支持DeviceOrientationEvent');
- }
- }
- function handleMotionEvent(event) {
- const x = event.accelerationIncludingGravity.x;
- const y = event.accelerationIncludingGravity.y;
- const z = event.accelerationIncludingGravity.z;
- console.log(`DeviceMotionEvent data: ${event.timeStamp}, ${x}, ${y}, ${z}`);
- }
- function listenDeviceOrientationEvent() {
- removeDeviceOrientationEvent();
- if ('DeviceOrientationEvent' in window) {
- window.addEventListener('deviceorientation', handleOrientationEvent, false);
- } else {
- console.log('不支持DeviceOrientationEvent');
- }
- }
- function removeDeviceOrientationEvent() {
- if ('DeviceOrientationEvent' in window) {
- window.removeEventListener('deviceorientation', handleOrientationEvent, false);
- } else {
- console.log('不支持DeviceOrientationEvent');
- }
- }
- function listenDeviceOrientationEvent2() {
- removeDeviceOrientationEvent2();
- if ('DeviceOrientationEvent' in window) {
- window.addEventListener('deviceorientationabsolute', handleOrientationEvent, false);
- } else {
- console.log('不支持DeviceOrientationEvent');
- }
- }
- function removeDeviceOrientationEvent2() {
- if ('DeviceOrientationEvent' in window) {
- window.removeEventListener('deviceorientationabsolute', handleOrientationEvent, false);
- } else {
- console.log('不支持DeviceOrientationEvent');
- }
- }
- function handleOrientationEvent(event) {
- console.log(`DeviceOrientationEvent data: ${event.timeStamp}, ${event.absolute}, ${event.alpha}, ${event.beta}, ${event.gamma}`);
- }
- </script>
- </head>
- <body>
- <div id="dcontent" class="dcontent">
- <h3>运动和方向:</h3>
- <ul class="dlist">
- <li><button type="button" onclick="getAccelerometer()">加速度</button></li>
- <li><button type="button" onclick="getGyroscope()">陀螺仪</button></li>
- <li><button type="button" onclick="getAbsoluteOrientationSensor()">设备方向(绝对定位)</button></li>
- <li><button type="button" onclick="listenDeviceMotionEvent()">设备运动事件</button></li>
- <li><button type="button" onclick="listenDeviceOrientationEvent()">设备方向事件</button></li>
- <li><button type="button" onclick="listenDeviceOrientationEvent2()">设备方向事件(绝对定位)</button></li>
- </ul>
- </div>
- </body>
- </html>
复制代码 
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |