当前位置:网站首页>运动App如何实现端侧后台保活,让运动记录更完整?
运动App如何实现端侧后台保活,让运动记录更完整?
2022-06-30 10:01:00 【HMS Core】
你在锻炼健身时,有没有遇到这样的情况?辛辛苦苦锻炼了几小时,却发现App停止了运行,本次运动并没有被记录到App上,从而失去了一个查看完整运动数据的机会?
运动类App是通过手机或者穿戴设备的传感器,来识别运动状态并反馈给用户的,App能否在手机后台时刻保持运行是影响运动数据完整性的关键因素。为了满足用户查看完整运动数据的需求,运动类App都希望在设备后台保活,并通过传感器实时记录用户的运动数据。但大部分手机厂商为了节省电量,一旦应用处于后台就会被系统限制甚至强制关闭,导致最终呈现给用户的运动记录不完整。
运动类App要想实现端侧后台保活,目前通常有两种解决办法:
引导用户在手机上手动设置保活,如关闭电池优化,允许App后台运行。这种方法缺点在于操作步骤较复杂,用户学习成本较高。
可以通过集成华为运动健康服务来解决此问题,运动健康服务提供支持后台保活的运动记录API,集成该能力后应用能够在用户的锻炼过程中在华为手机后台保持运行,从而实现用户锻炼过程中的运动记录不间断。
那如何实现后台保活功能呢?以下是详细的集成步骤。
集成步骤
请参考开发准备完成申请Health Kit服务,勾选产品必需申请的数据权限并集成SDK。
调用后台保活功能需申请运动记录读取权限,再获取用户授权完成权限申请。
为保证您的应用不被系统冻结,需要开启一个前台服务Foreground services,在前台服务中调用ActivityRecordsController方法创建允许后台运行的运动记录;
调用ActivityRecordsController的beginActivityRecord接口开始允许后台运行的运动记录,默认会申请允许应用后台运行时长10分钟;
// 请注意此处的this为Activity对象ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this); // 1.构造新运动记录开始时间long startTime = Calendar.getInstance().getTimeInMillis(); // 2.构造ActivityRecord对象,设置运动记录开始时间 ActivityRecord activityRecord = new ActivityRecord.Builder() .setId("MyBeginActivityRecordId") .setName("BeginActivityRecord") .setDesc("This is ActivityRecord begin test!") .setActivityTypeId(HiHealthActivities.RUNNING) .setStartTime(startTime, TimeUnit.MILLISECONDS) .build(); // 3.构建应用运动记录运行中展示的页面, MyActivity需替换成自身的Activity类ComponentName componentName = new ComponentName(this, MyActivity.class);// 4.构建运动记录后台运行状态变化监听器OnActivityRecordListener activityRecordListener = new OnActivityRecordListener() { @Override public void onStatusChange(int statusCode) { Log.i("ActivityRecords", "onStatusChange statusCode:" + statusCode); }};// 5.调用启动新运动记录API接口beginActivityRecordTask<Void> task1 = activityRecordsController.beginActivityRecord(activityRecord, componentName, activityRecordListener); // 6.添加启动ActivityRecord成功 task1.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.i("ActivityRecords", "MyActivityRecord begin success"); } // 7.添加启动ActivityRecord失败}).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { String errorCode = e.getMessage(); String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode)); Log.i("ActivityRecords", errorCode + ": " + errorMsg); } });- 若用户运动时间较长,每临近10分钟(小于10分钟)需调用ActivityRecordsController的continueActivityRecord接口续申请后台保活10分钟;
// 请注意此处的this为Activity对象ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this); // 调用continueActivityRecord方法为指定运动记录续申请允许后台运行,入参为ActivityRecord的ID字符串 Task<Void> endTask = activityRecordsController.continueActivityRecord("MyBeginActivityRecordId");endTask.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.i("ActivityRecords", "continue backgroundActivityRecord was successful!"); }}).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { Log.i("ActivityRecords", "continue backgroundActivityRecord error"); }});- 当用户运动结束时,调用ActivityRecordsController的endActivityRecord接口停止该运动记录,同时取消应用后台保活;
// 请注意此处的this为Activity对象final ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this);// 调用endActivityRecord接口停止运动记录,入参为ActivityRecord的ID字符串或者null// 入参为ID字符串时,停止当前应用指定ID的运动记录// 入参为null时,停止该应用当前所有的未停止运动记录Task<List<ActivityRecord>> endTask = activityRecordsController.endActivityRecord("MyBeginActivityRecordId");endTask.addOnSuccessListener(new OnSuccessListener<List<ActivityRecord>>() { @Override public void onSuccess(List<ActivityRecord> activityRecords) { Log.i("ActivityRecords","MyActivityRecord End success"); // 返回停止成功的运动记录列表 if (activityRecords.size() > 0) { for (ActivityRecord activityRecord : activityRecords) { DateFormat dateFormat = DateFormat.getDateInstance(); DateFormat timeFormat = DateFormat.getTimeInstance(); Log.i("ActivityRecords", "Returned for ActivityRecord: " + activityRecord.getName() + "\n\tActivityRecord Identifier is " + activityRecord.getId() + "\n\tActivityRecord created by app is " + activityRecord.getPackageName() + "\n\tDescription: " + activityRecord.getDesc() + "\n\tStart: " + dateFormat.format(activityRecord.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(activityRecord.getStartTime(TimeUnit.MILLISECONDS)) + "\n\tEnd: " + dateFormat.format(activityRecord.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(activityRecord.getEndTime(TimeUnit.MILLISECONDS)) + "\n\tActivity:" + activityRecord.getActivityType()); } } else { // 没有停止成功返回null Log.i("ActivityRecords","MyActivityRecord End response is null"); } }}).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { String errorCode = e.getMessage(); String errorMsg = HiHealthStatusCodes.getStatusCodeMessage(Integer.parseInt(errorCode)); Log.i("ActivityRecords",errorCode + ": " + errorMsg); }});需要注意的是,由于端侧后台保活API属于敏感权限,运动类应用接入时需进行人工审核,确保数据安全、流程合规才能上架。
了解更多详情>>
访问华为开发者联盟官网
获取开发指导文档
华为移动服务开源仓库地址:GitHub、Gitee
关注我们,第一时间了解 HMS Core 最新技术资讯~
边栏推荐
- 微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条...
- Auto Seg-Loss: 自动损失函数设计
- R language plot visualization: use plot to visualize the prediction confidence of the multi classification model, the prediction confidence of each data point of the model in the 2D grid, and the conf
- 【Rust每周一库】num-bigint - 大整数
- mysql数据库基础:视图、变量
- Arm新CPU性能提升22%,最高可组合12核,GPU首配硬件光追,网友:跟苹果的差距越来越大了...
- How to seize the opportunity of NFT's "chaos"?
- 马斯克推特粉丝过亿了,但他在线失联已一周
- Musk has more than 100 million twitter fans, but he has been lost online for a week
- I found a wave of "alchemy artifact" in the goose factory. The developer should pack it quickly
猜你喜欢

Test memory read rate

GeoffreyHinton:我的五十年深度学习生涯与研究心法

Getting started with X86 - take over bare metal control

Voir le changement technologique à travers la Légion Huawei (5): Smart Park

mysql数据库基础:约束、标识列

scratch绘制正方形 电子学会图形化编程scratch等级考试二级真题和答案解析2022年6月

Oracle creates a stored procedure successfully, but the compilation fails

最新SCI影响因子公布:国产期刊最高破46分!网友:算是把IF玩明白了

The preliminary round of the sixth season of 2022 perfect children's model Hefei competition area was successfully concluded

6. Redis new data type
随机推荐
马斯克推特粉丝过亿了,但他在线失联已一周
CVPR 2022 | Tsinghua & bytek & JD put forward BRT: Bridging Transformer for vision and point cloud 3D target detection
Who should the newly admitted miners bow to in front of the chip machine and the graphics card machine
The latest SCI impact factor release: the highest score of domestic journals is 46! Netizen: I understand if
R语言plotly可视化:使用plotly可视化多分类模型的预测置信度、模型在2D网格中每个数据点预测的置信度、置信度定义为在某一点上最高分与其他类别得分之和之间的差值
Migrate full RT thread to gd32f4xx (detailed)
What is the real performance of CK5, the king machine of CKB?
Skill combing [email protected] somatosensory manipulator
I found a wave of "alchemy artifact" in the goose factory. The developer should pack it quickly
半钢同轴射频线的史密斯圆图查看和网络分析仪E5071C的射频线匹配校准
六月集训(第30天) —— 拓扑排序
转卡通学习笔记
"Kunming City coffee map" activity was launched again
The famous painter shiguoliang's "harvest season" digital collection was launched on the Great Wall Digital Art
MySQL log management, backup and recovery of databases (2)
A brief introduction to database mysql
mysql数据库基础:视图、变量
ArcGIS Pro脚本工具(6)——修复CAD图层数据源
Didi open source agile test case management platform!
The digital collection of sunanmin's lotus heart clearing was launched on the Great Wall Digital Art