我对Google Fit STEP计数API有一些疑问。
问题是:
1)如果手机没有安装Google Fit应用,可以在myApp中使用google fit API。
2)使用Google Fit的Recording API时,是应该记录SENSOR DATA还是仅记录STEP_DELTA数据?正如我注意到的那样,Google Fit与其他健身应用程序的步数不同。谷歌适合应用程序的例子它只有20个步骤,但在其他健身应用程序我有2561步骤。
3)对于步数为零的日子,googleFit不会检索当天的数据,我该如何解决?
我很抱歉这不是基于代码的。
订阅Google适合RecordingAPI的代码
public void subscribe() {
mClient = new GoogleApiClient.Builder(mContext)
.addApi(Fitness.RECORDING_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.useDefaultAccount()
.build();
//to request background collection of data
Fitness.RecordingApi.subscribe(mClient, DataType.TYPE_STEP_COUNT_DELTA);
Fitness.getRecordingClient(mContext, GoogleSignIn.getLastSignedInAccount(mContext))
.subscribe(DataType.TYPE_ACTIVITY_SAMPLES)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i("TAG1", "Successfully subscribed");
accessGoogleFit();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("TAG1", "There was a problem subscripting");
}
});
}
正在通过HistoricalAPI检索数据
private void accessGoogleFit() {
mClient = new GoogleApiClient.Builder(mContext)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.CONFIG_API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
//fetch data
new FetchStepsAsync().execute();
}
@Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i("TAG1", "Connection lost,Cause: network lost");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i("TAG1", "Connection lost, service disconnected");
}
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
Log.i("TAG1", "Connection failed. Cause:" + result.toString());
if (!result.hasResolution()) {
//show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), getActivity(), 0).show();
return;
}
//the failure has a resolution
if (!authInProcess) {
try {
Log.i("TAG1", "Attempting to resolve failed connection");
authInProcess = true;
result.startResolutionForResult(getActivity(), GOOGLE_FIT_PERMISSIONS_REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
Log.e("TAG1", "Exception while starting resolution activity", e);
}
}
}
})
.build();
mClient.connect();
}
private class FetchStepsAsync extends AsyncTask<Object, Object, Long> {
protected Long doInBackground(Object... params) {
long total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.TYPE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
if (totalSet != null) {
total = totalSet.isEmpty() ? 0 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
}
} else {
Log.w("TAG1", "There was a problem getting the step count.");
}
return total;
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
//Total steps
Log.i("TAG1", "Total steps:" + aLong);
edSteps.setText(aLong.toString());
}
}
对于您的第一个问题:是的,无论Google Fit应用是谁,您的应用都会收到合适的数据。
对于您的第二个问题:需要订阅传感器API,如果您希望用户的当前活动在应用中显示,那么您需要订阅传感器API(例如,在您的应用中走动时显示步骤更新)。否则,如果您只需要步骤数据,则可以使用History API。
对于第3个问题:是的,fit API不会为空步骤检索任何数据,您需要添加一些解决方法来调整它。
val stepsHistoryBeforeALUCallback = ResultCallback<DataReadResult> { dataReadResult ->
val stepBucketList: MutableList<DataPoint> = ArrayList()
if(dataReadResult.buckets.size > 0){
dataReadResult.buckets.forEachIndexed { index, it ->
val dataSets = it.dataSets
dataSets.forEach { dataSet ->
if(dataSet.dataPoints.size == 0)
//for this day, the fit api does not gives anu dataPoints
stepBucketList.add(getEmptyDataPoint(index))
else
stepBucketList.add(dataSet.dataPoints[0])
}
}
}
}
并且下面的代码返回0步的空数据点
fun getEmptyDataPoint(index: Int): DataPoint{
var time = (FitVariable.appLastUpdateTime*1000) + (index * (24*60*60*1000))
//above calculated time is time for which you need empty data point, please add your own logic. You can take index as reference
val dataSource = DataSource.Builder()
.setAppPackageName(BuildConfig.APPLICATION_ID)
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setStreamName("step count")
.setType(DataSource.TYPE_RAW)
.build()
// Create a data set
val stepCountDelta = 0
val dataSet = DataSet.create(dataSource)
// For each data point, specify a start time, end time, and the data value -- in
this
case,
// the number of new steps.
val dataPoint = dataSet.createDataPoint().setTimeInterval(time,
time,TimeUnit.MILLISECONDS)
dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta)
return dataPoint
}