找回密码
 立即注册
搜索

如何全局监听步数变化?

1
回复
339
查看
[复制链接]

46

主题

47

帖子

465

积分

 楼主| 2021-7-2 09:22:41 显示全部楼层 |阅读模式

如何全局监听步数变化?


回复

使用道具 举报

23

主题

142

帖子

825

积分

2021-7-2 09:24:14 显示全部楼层

在app.ux中调用传感器接口,每个页面使用watch监听获取当前步数变化即可。

  1. 在app.ux中定义全局对象,见如下代码中的localeData对象,该对象中定义了属性currentStep,用来保存sensor接口返回的结果。

  2. 在app.ux生命周期onCreate()中调用sensor计步传感器接口。

  3. 具体页面调用$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>

回复

使用道具 举报

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