我知道這是一個老問題,但我需要幫助這個太,所以我會盡力幫助:
你的活動需要實現這一點:
implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
創建此之前的onCreate變量:public GoogleApiClient mGoogleApiClient = null;
裏面的onCreate這樣寫:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(this)
.enableAutoManage(this, 0, this)
.build();
不要忘記OAuth身份驗證。
然後,你需要這樣的方法:
public void onConnected(@Nullable Bundle bundle) {
Log.e("HistoryAPI", "onConnected");
}
@Override
public void onConnectionSuspended(int i) {
Log.e("HistoryAPI", "onConnectionSuspended");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.e("HistoryAPI", "onConnectionFailed");
}
public void onClick(View v) {
}
在此之後,您將創建這個方法,讀步進計數器(谷歌飛度API盡數)
public void displayStepDataForToday() {
DailyTotalResult result = Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA).await(1, TimeUnit.MINUTES);
showDataSet(result.getTotal());
}
這是是showDataSet裏面displayStepDataForToday()
private void showDataSet(DataSet dataSet) {
Log.e("History", "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getDateInstance();
DateFormat timeFormat = DateFormat.getTimeInstance();
for (DataPoint dp : dataSet.getDataPoints()) {
Log.e("History", "Data point:");
Log.e("History", "\tType: " + dp.getDataType().getName());
Log.e("History", "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
Log.e("History", "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
for(Field field : dp.getDataType().getFields()) {
Log.e("History", "\tField: " + field.getName() +
" Value: " + dp.getValue(field));
//writeToFile(dp.getValue(field).asInt());
//this is how I save the data (wit the writeToFile)
}
}
}
最後你需要創建一個類(在你的內部活動)使用displayStepDataForToday()
方法
public class ViewTodaysStepCountTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
displayStepDataForToday();
return null;
}
}
你只需要當你要開始活動,然後得到它的值。這將在後臺運行並根據需要進行更新。如果你想這個代碼更新快,你可以做一些研究,但我認爲你需要改變這一行:
public void displayStepDataForToday() {
DailyTotalResult result = Fitness.HistoryApi.readDailyTotal(mGoogleApiClient, DataType.TYPE_STEP_COUNT_DELTA).await(1, TimeUnit.MINUTES);
這可能會幫助一些http://www.gadgetsaint.com/android/update-calories -steps,谷歌配合-API /#。WPFGK1N97BI – ASP