鸿蒙NEXT版实战开发:ArkWeb设置根本属性和变乱(利用运动和方向传感器) ...

打印 上一主题 下一主题

主题 1582|帖子 1582|积分 4746

往期鸿蒙全套实战精彩文章必看内容:



  • 鸿蒙开发核心知识点,看这篇文章就够了
  • 最新版!鸿蒙HarmonyOS Next应用开发实战学习路线
  • 鸿蒙HarmonyOS NEXT开发技能最全学习路线指南
  • 鸿蒙应用开发实战项目,看这一篇文章就够了(部门项目附源码)

利用运动和方向传感器

Web组件可以通过W3C尺度协议接口对接运动和方向相关的传感器。开发者在利用该功能中的加速率、陀螺仪及装备运动变乱接口时,需在设置文件中声明相应的传感器权限。


  • 利用加速率和装备运动变乱接口前请在module.json5中添加加速率权限。
    1. "requestPermissions":[
    2.    {
    3.      "name" : "ohos.permission.ACCELEROMETER"
    4.    }
    5. ]
    复制代码
  • 利用陀螺仪接口前请在module.json5中添加陀螺仪权限。
    1. "requestPermissions":[
    2.    {
    3.      "name" : "ohos.permission.GYROSCOPE"
    4.    }
    5. ]
    复制代码
Web组件在对接运动和方向传感器时,需设置onPermissionRequest接口,通过该接口接收权限请求通知。
通过在JavaScript中调用下面这些W3C尺度协议接口,可以访问运动和方向传感器。
接口名称是否支持阐明Accelerometer加速率支持-Gyroscope陀螺仪支持-AbsoluteOrientationSensor绝对定位支持-RelativeOrientationSensor相对定位不支持传感器数据暂不支持DeviceMotionEvent装备运动变乱支持-DeviceOrientationEvent装备方向变乱支持可获取绝对定位方向 RelativeOrientationSensor受限于利用到的传感器功能暂未设置,暂不支持利用该接口监听装备相对定位方向数据。
在下面的示例中,点击index.html前端页面各种按钮,监听相应数据。


  • 应用侧代码。
    1. import { webview } from '@kit.ArkWeb';
    2. import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit';
    3. import { BusinessError } from '@kit.BasicServicesKit';
    4. @Entry
    5. @Component
    6. struct WebComponent {
    7.   controller: webview.WebviewController = new webview.WebviewController()
    8.   aboutToAppear() {
    9.     // 配置Web开启调试模式
    10.     webview.WebviewController.setWebDebuggingAccess(true);
    11.     // 访问控制管理, 获取访问控制模块对象。
    12.     let atManager = abilityAccessCtrl.createAtManager();
    13.     try {
    14.       atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.ACCELEROMETER', 'ohos.permission.GYROSCOPE']
    15.         , (err: BusinessError, data: PermissionRequestResult) => {
    16.         console.info('data:' + JSON.stringify(data));
    17.         console.info('data permissions:' + data.permissions);
    18.         console.info('data authResults:' + data.authResults);
    19.       })
    20.     } catch (error) {
    21.       console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
    22.     }
    23.   }
    24.   build() {
    25.     Column() {
    26.       Web({ src: $rawfile('index.html'), controller: this.controller })
    27.         .onPermissionRequest((event) => {
    28.           if (event) {
    29.             AlertDialog.show({
    30.               title: 'title',
    31.               message: 'text',
    32.               primaryButton: {
    33.                 value: 'deny',
    34.                 action: () => {
    35.                   event.request.deny();
    36.                 }
    37.               },
    38.               secondaryButton: {
    39.                 value: 'onConfirm',
    40.                 action: () => {
    41.                   event.request.grant(event.request.getAccessibleResource());
    42.                 }
    43.               },
    44.               autoCancel: false,
    45.               cancel: () => {
    46.                 event.request.deny();
    47.               }
    48.             })
    49.           }
    50.         })
    51.     }
    52.   }
    53. }
    复制代码
  • 前端页面index.html代码。
    1. <!DOCTYPE HTML>
    2. <html>
    3. <head>
    4.     <meta charset="utf-8" />
    5.     <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    6.     <meta name="misapplication-tap-highlight" content="no" />
    7.     <meta name="HandheldFriendly" content="true" />
    8.     <meta name="MobileOptimized" content="320" />
    9.     <title>运动和方向传感器</title>
    10.     <meta charset="UTF-8">
    11.     <style>
    12.         body {
    13.             font-family: Arial, sans-serif;
    14.         }
    15.     </style>
    16.     <script type="text/javascript">
    17.         function getAccelerometer() {
    18.             var acc = new Accelerometer({frequency: 60});
    19.             acc.addEventListener('activate', () => console.log('Ready to measure.'));
    20.             acc.addEventListener('error', error => console.log(`Error: ${error.name}`));
    21.             acc.addEventListener('reading', () => {
    22.                 console.log(`[doc_sensor]Accelerometer ${acc.timestamp}, ${acc.x}, ${acc.y}, ${acc.z}.`);
    23.             });
    24.             acc.start();
    25.         }
    26.         function getGyroscope() {
    27.             var gyr = new Gyroscope({frequency: 60});
    28.             gyr.addEventListener('activate', () => console.log('Ready to measure.'));
    29.             gyr.addEventListener('error', error => console.log(`Error: ${error.name}`));
    30.             gyr.addEventListener('reading', () => {
    31.                 console.log(`[doc_sensor]Gyroscope ${gyr.timestamp}, ${gyr.x}, ${gyr.y}, ${gyr.z}.`);
    32.             });
    33.             gyr.start();
    34.         }
    35.         function getAbsoluteOrientationSensor() {
    36.             var aos = new AbsoluteOrientationSensor({frequency: 60});
    37.             aos.addEventListener('activate', () => console.log('Ready to measure.'));
    38.             aos.addEventListener('error', error => console.log(`Error: ${error.name}`));
    39.             aos.addEventListener('reading', () => {
    40.                 console.log(`AbsoluteOrientationSensor data: ${ros.timestamp}, ${ros.quaternion}`);
    41.             });
    42.             aos.start();
    43.         }
    44.         function listenDeviceMotionEvent() {
    45.             removeDeviceMotionEvent();
    46.             if ('DeviceMotionEvent' in window) {
    47.                 window.addEventListener('devicemotion', handleMotionEvent, false);
    48.             } else {
    49.               console.log('不支持DeviceMotionEvent');
    50.             }
    51.         }
    52.         function removeDeviceMotionEvent() {
    53.             if ('DeviceMotionEvent' in window) {
    54.               window.removeEventListener('devicemotion', handleMotionEvent, false);
    55.             } else {
    56.               console.log('不支持DeviceOrientationEvent');
    57.             }
    58.         }
    59.         function handleMotionEvent(event) {
    60.             const x = event.accelerationIncludingGravity.x;
    61.             const y = event.accelerationIncludingGravity.y;
    62.             const z = event.accelerationIncludingGravity.z;
    63.             console.log(`DeviceMotionEvent data: ${event.timeStamp}, ${x}, ${y}, ${z}`);
    64.         }
    65.         function listenDeviceOrientationEvent() {
    66.             removeDeviceOrientationEvent();
    67.             if ('DeviceOrientationEvent' in window) {
    68.                 window.addEventListener('deviceorientation', handleOrientationEvent, false);
    69.             } else {
    70.                 console.log('不支持DeviceOrientationEvent');
    71.             }
    72.         }
    73.         function removeDeviceOrientationEvent() {
    74.             if ('DeviceOrientationEvent' in window) {
    75.               window.removeEventListener('deviceorientation', handleOrientationEvent, false);
    76.             } else {
    77.               console.log('不支持DeviceOrientationEvent');
    78.             }
    79.         }
    80.         function listenDeviceOrientationEvent2() {
    81.             removeDeviceOrientationEvent2();
    82.             if ('DeviceOrientationEvent' in window) {
    83.                 window.addEventListener('deviceorientationabsolute', handleOrientationEvent, false);
    84.             } else {
    85.                 console.log('不支持DeviceOrientationEvent');
    86.             }
    87.         }
    88.         function removeDeviceOrientationEvent2() {
    89.             if ('DeviceOrientationEvent' in window) {
    90.               window.removeEventListener('deviceorientationabsolute', handleOrientationEvent, false);
    91.             } else {
    92.               console.log('不支持DeviceOrientationEvent');
    93.             }
    94.         }
    95.         function handleOrientationEvent(event) {
    96.             console.log(`DeviceOrientationEvent data: ${event.timeStamp}, ${event.absolute}, ${event.alpha}, ${event.beta}, ${event.gamma}`);
    97.         }
    98.     </script>
    99. </head>
    100. <body>
    101. <div id="dcontent" class="dcontent">
    102.     <h3>运动和方向:</h3>
    103.     <ul class="dlist">
    104.         <li><button type="button" onclick="getAccelerometer()">加速度</button></li>
    105.         <li><button type="button" onclick="getGyroscope()">陀螺仪</button></li>
    106.         <li><button type="button" onclick="getAbsoluteOrientationSensor()">设备方向(绝对定位)</button></li>
    107.         <li><button type="button" onclick="listenDeviceMotionEvent()">设备运动事件</button></li>
    108.         <li><button type="button" onclick="listenDeviceOrientationEvent()">设备方向事件</button></li>
    109.         <li><button type="button" onclick="listenDeviceOrientationEvent2()">设备方向事件(绝对定位)</button></li>
    110.     </ul>
    111. </div>
    112. </body>
    113. </html>
    复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

渣渣兔

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表