用你的应用程序在后台进行锻炼跟踪
一篇关于如何在后台对健身应用的锻炼数据进行跟踪的文章。
因为健身应用在后台停止运行而失去锻炼的轨迹,这可能是非常令人沮丧的。这发生在你关闭屏幕或在锻炼期间有另一个应用程序在前面听音乐或看视频的时候。说到这里,你所有的汗水和努力都白费了!
健身应用程序通过使用手机或可穿戴设备上的传感器,实时识别和显示用户的锻炼状态。只有当它们能在后台持续运行时,它们才能获得并向用户显示完整的锻炼记录。由于大多数用户会关闭屏幕,或在锻炼期间使用其他应用程序,因此在后台保持活力一直是健身应用程序的必备功能。然而,为了节省电池电量,一旦应用程序在后台运行,大多数手机会限制甚至强行关闭,导致锻炼数据不完整。当建立你自己的健身应用程序时,必须牢记这一限制。
有两种久经考验的方法来保持健身应用在后台运行。
- 指导用户手动配置其手机或可穿戴设备上的设置,例如,禁用电池优化,或允许特定的应用程序在后台运行。然而,这个过程可能很麻烦,而且不容易操作。
- 或者,将开发工具整合到你的应用程序中,例如,健康工具包,它提供的API允许你的应用程序在锻炼期间在后台持续运行,而不会丢失任何锻炼数据的跟踪。
下面详细介绍整合这个工具包的过程。
集成程序
1.在您开始之前,请在HUAWEI Developers上申请Health Kit,选择所需的数据范围,并集成Health SDK。
2.获得用户授权,并申请读写锻炼记录的范围。
3.启用前台服务,防止你的应用被系统冻结,并在前台服务中调用ActivityRecordsController来创建可以在后台运行的锻炼记录。
4.调用ActivityRecordsController的beginActivityRecord来启动锻炼记录。默认情况下,一个应用程序将被允许在后台运行10分钟。
// Note that this refers to an Activity object.
ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this);
// 1. Build the start time of a new workout record.
long startTime = Calendar.getInstance().getTimeInMillis();
// 2. Build the ActivityRecord object and set the start time of the workout record.
ActivityRecord activityRecord = new ActivityRecord.Builder()
.setId("MyBeginActivityRecordId")
.setName("BeginActivityRecord")
.setDesc("This is ActivityRecord begin test!")
.setActivityTypeId(HiHealthActivities.RUNNING)
.setStartTime(startTime, TimeUnit.MILLISECONDS)
.build();
// 3. Construct the screen to be displayed when the workout record is running in the background. Note that you need to replace MyActivity with the Activity class of the screen.
ComponentName componentName = new ComponentName(this, MyActivity.class);
// 4. Construct a listener for the status change of the workout record.
OnActivityRecordListener activityRecordListener = new OnActivityRecordListener() {
@Override
public void onStatusChange(int statusCode) {
Log.i("ActivityRecords", "onStatusChange statusCode:" + statusCode);
}
};
// 5. Call beginActivityRecord to start the workout record.
Task<Void> task1 = activityRecordsController.beginActivityRecord(activityRecord, componentName, activityRecordListener);
// 6. ActivityRecord is successfully started.
task1.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i("ActivityRecords", "MyActivityRecord begin success");
}
// 7. ActivityRecord fails to be started.
}).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);
}
});
5.如果锻炼持续超过10分钟,每次在10分钟结束前调用ActivityRecord的continueActivityController,以申请锻炼继续10分钟。
// Note that this refers to an Activity object.
ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this);
// Call continueActivityRecord and pass the workout record ID for the record to continue in the background.
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");
}
});
6.当用户完成锻炼时,调用ActivityRecordsController的endActivityRecord来停止记录,并停止在后台保持其活力。
// Note that this refers to an Activity object.
final ActivityRecordsController activityRecordsController = HuaweiHiHealth.getActivityRecordsController(this);
// Call endActivityRecord to stop the workout record. The input parameter is null or the ID string of ActivityRecord.
// Stop a workout record of the current app by specifying the ID string as the input parameter.
// Stop all workout records of the current app by specifying null as the input parameter.
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");
// Return the list of workout records that have stopped.
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 will be returned if the workout record hasn't stopped.
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以保持你的应用程序在后台运行是一个敏感的操作,需要人工批准。在申请发布之前,请确保你的应用程序符合数据安全和合规性要求。
总结
健身应用在保持用户健康和积极性方面发挥着重要作用,它为用户提供量身定做的健身方案,帮助他们建立现实的健身目标,并跟踪用户的健康和健身情况。为了实时监测锻炼记录,健身应用程序必须能够连续运行,即使屏幕已经关闭,或者另一个应用程序已经打开在前面运行。做到这一点的一个方法是整合一项服务,提供在后台保持锻炼记录的能力,这有助于大大改善用户使用健身应用程序的体验。让我们开始吧!