/**
* Register fitness listeners for all the required data types
*/
private void registerFitnessListeners() {
mStepCountListener =
new OnDataPointListener() {
@Override
public void onDataPoint(DataPoint dataPoint) {
for (Field field : dataPoint.getDataType().getFields()){
int stepDelta = dataPoint.getValue(field).asInt();
mSteps += stepDelta;
stepCountTextView.setText(
"Detected Datapoint field: " + field.getName()
+ "\nDetected Datapoint value:" + mSteps);
}
}
};
Fitness.getSensorsClient(mContext, mGoogleSignInAccount)
.add(
new SensorRequest.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setSamplingRate(1, TimeUnit.SECONDS)
.setMaxDeliveryLatency(3, TimeUnit.SECONDS)
.setFastestRate(1, TimeUnit.SECONDS)
.build(),
mStepCountListener)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Log.d(TAG, "Listener registered");
}else{
Log.e(TAG, "Listener not registered", task.getException());
}
}
});
}
/**
* Unregisters the listener with the Sensors API.
*/
private void unregisterFitnessListeners(){
Fitness.getSensorsClient(mContext, mGoogleSignInAccount)
.remove(mStepCountListener)
.addOnCompleteListener(new OnCompleteListener<Boolean>() {
@Override
public void onComplete(@NonNull Task<Boolean> task) {
if(task.isSuccessful() && task.getResult()){
Log.d(TAG, "Listener was removed");
}else{
Log.d(TAG, "Listener was not removed");
}
}
});
}
当我尝试注销OnDataPointListener进行计数时,我的LogCat总是说未删除侦听器。我知道task.getResult()总是返回false。为什么会这样呢?难道我做错了什么?如何删除监听器?
编辑:我已经在Google的问题跟踪器上创建了一个问题。您可以对其加注星标,以便快速修复它。这是链接
答案 0 :(得分:1)
即使我遇到了类似的问题,但后来我还是尝试解决SensorsApi
GoogleApiClient googleApiClient = Fitness
.getSensorsClient(context, GoogleSignIn.getLastSignedInAccount(context))
.asGoogleApiClient();
Fitness.SensorsApi.remove(googleApiClient, mListener).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.d(TAG, "onResult: Successfully removed sensor api");
} else {
Log.e(TAG, "onResult: Unable to remove sensor api");
}
}
});
它就像一种魅力!
答案 1 :(得分:0)
我发现该错误仅存在于Google Fit SDK的最新版本中。旧版本可以正常工作。因此,将版本更改为以下版本即可:'com.google.android.gms:play-services-fitness:12.0.1'