Я интегрировал googleFit в приложение для Android.
Я использую API истории, чтобы получать обновления по требованию, а также подписываться на обновления. Вот фрагмент кода, который я добавил. Я использую для инициализации Google Fit и получить счетчик шагов. Мне нужно перезвонить единицу времени с счетчика шагов в ожидании намерения отправить на сервер.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SESSIONS_API)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.RECORDING_API)
.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
.enableAutoManage(this, 0, this)
.build();
public void subscribe() {
// To create a subscription, invoke the Recording API. As soon as the subscription is
// active, fitness data will start recording.
Fitness.RecordingApi.subscribe(mGoogleApiClient, DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setResultCallback(status -> {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.e(TAG, "Existing subscription for activity detected.");
} else {
Log.e(TAG, "Successfully subscribed!");
}
} else {
Log.w(TAG, "There was a problem subscribing.");
}
});
}
public void unSubscribe() {
// To create a subscription, invoke the Recording API. As soon as the subscription is
// active, fitness data will start recording.
Fitness.RecordingApi.unsubscribe(mGoogleApiClient, DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setResultCallback(status -> {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.e(TAG, "Existing subscription for activity detected.");
} else {
Log.e(TAG, "Successfully subscribed!");
}
} else {
Log.w(TAG, "There was a problem subscribing.");
}
});
}
long total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
} else {
Log.e(TAG, "There was a problem getting the step count.");
}
Log.e(TAG, "TOTAL STEPS : " + total);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
Log.e(TAG, "onConnection DisConnected");
}