我正试图在我的裁判观察中记录体育活动期间的Google健身会话。我在一段时间的开始时开始一个会话,然后在期间结束时停止它。
当我使用此代码启动Fitness会话时,有时会遇到一个有趣的异常:
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()会查看&#34; present&#34;当新的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来获得&#34;当前时间&#34;)和(b)这是一个Builder类型调用的常见模式?