在app.ux中调用传感器接口,每个页面使用watch监听获取当前步数变化即可。 在app.ux中定义全局对象,见如下代码中的localeData对象,该对象中定义了属性currentStep,用来保存sensor接口返回的结果。 在app.ux生命周期onCreate()中调用sensor计步传感器接口。 具体页面调用$watch()函数监听步骤1中的currentStep,实时获取步数。
具体示例代码如下。 app.ux代码: <script> import sensor from '@system.sensor' module.exports = { onCreate() { console.info('Application onCreate'); this.listenStep(); }, onDestroy() { console.info('Application onDestroy'); sensor.unsubscribeStepCounter(); }, listenStep: function () { console.info("currentStep START "); var that = this sensor.subscribeStepCounter({ callback: function (ret) { that.data.localeData.currentStep = ret.steps; console.info("currentStep CALLBACK :" + that.data.localeData.currentStep); }, fail: function (erromsg, errocode) { console.log('currentStep.subscribe----------' + errocode + ': ' + erromsg) } }) }, data: { localeData: { currentStep: '', } } } </script>
页面hello.ux代码:
<template> <!-- Only one root node is allowed in template. --> <div class="container"> <text class="title">当前步数:{{ currentStep.currentStep }}</text> </div> </template> <style> .container { flex-direction: column; justify-content: center; align-items: center; } .title { font-size: 100px; } </style> <script> module.exports = { data: { currentStep: {}, }, onInit() { this.$page.setTitleBar({ text: 'menu', textColor: '#ffffff', backgroundColor: '#007DFF', backgroundOpacity: 0.5, menu: true }); this.currentStep = this.$app.$def.data.localeData; this.$watch('currentStep.currentStep', 'listenStep'); }, listenStep: function (newValue, oldValue) { console.info("listenStep newValue= " + newValue); }, } </script> |