文档开发者中心
我的

如何全局监听步数变化

背景

   快应用提供传感器接口sensor,能够监听用户当前累计记录的步数,开发者可以根据步数变化情况,提供不同的运动健康功能。如果在每个页面中都去监听步数变化,重复代码多,还容易遗漏,有没有一种方案可以做到全局监听呢?

    通过在快应用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>
点赞
1
收藏
1
回复
3
分享
举报
浏览537 发布于2021-06-26 06:06未知归属地
全部评论
最多点赞
最新发布
最早发布
谢谢版主,是为我目前你的工作而写的吗hhh
3楼回复于2021-07-15 07:02 未知归属地
不是很懂呀,但觉得很有知识
2楼回复于2021-07-03 02:59 未知归属地
老师发的东西真细致,很容易理解,感谢感谢
1楼回复于2021-06-28 04:24 未知归属地
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要发帖子

目录 收起
背景
实现方案
了解社区公约,与您携手共创和谐专业的开发者社区。