我正在尝试在我的裁判手表中记录体育活动期间的 Google Fit 会话。我在一个时期开始时开始一个会话,然后在这个时期结束时停止它。
当我使用以下代码开始健身课程时,有时会遇到一个有趣的异常:
private Session startFitSession(final Game currentGame) {
final Session fitSession;
try {
String sessionBaseName = currentGame.getGameTitle();
if (sessionBaseName.isEmpty()) sessionBaseName = currentGame.getGameLocation();
if (sessionBaseName.isEmpty()) sessionBaseName = RefWatchUtil.timeMsToString(currentGame.getActualStartMs(),RefWatchUtil.dateTimeFormatStart);
final String sessionName = sessionBaseName + ": "
+ String.format(getResources().getString(R.string.fitness_period_label),mCurrentPeriod);
//use this to try to avoid error message about creating a session in the future
final long startTime = System.currentTimeMillis()-TimeUnit.SECONDS.toMillis(10);
fitSession = new Session.Builder()
.setName(sessionName)
.setIdentifier(sessionName)
.setDescription(mCurrentGame.getGameDescription())
.setStartTime(startTime, TimeUnit.MILLISECONDS)
.setActivity(FitnessActivities.RUNNING_JOGGING)
.build();
Fitness.SessionsApi.startSession(mGoogleApiClient, fitSession)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Successfully started Session " + sessionName);
} else {
Log.i(TAG, "There was a problem starting the session " + sessionName
+ ": " + status.getStatusMessage());
}
}
});
} catch (RuntimeException e){
Log.i(TAG, "There was a runtime exception starting the session: " + e.getLocalizedMessage());
return null;
}
return fitSession;
}
例外是:
There was a runtime exception starting the session: Cannot start a session in the future
所以我突然想到 Session.Builder() 可能会像 new Builder() 调用一样查看“当前”,所以我更改为以下代码:
...
final long startTime = System.currentTimeMillis();
fitSession = new Session.Builder()
.setName(sessionName)
.setIdentifier(sessionName)
.setDescription(mCurrentGame.getGameDescription())
.setStartTime(startTime, TimeUnit.MILLISECONDS)
...
同样的错误。
所以现在我从 startTime 中减去任意 10 秒,这似乎解决了问题。
但是(a)有没有更好的方法来进行这个调用(afaict,你不能用 0 参数调用 setStartTime 来获取“当前时间”)和(b)这是 Builder 类型调用的常见模式吗?