我正在制作一款需要在后台计算步数的应用。在JobService类中,我想连接到GoogleFit API并阅读这些步骤。我遇到的问题是我无法通过GoogleFit进行连接。我的日志“工作”显示,但没有出现Fit连接的日志,这使我相信连接永远不会发生。我尝试在onCreate()和onStartJob()中启动客户端构建器,但都没有工作。有什么想法吗?
public class BackgroundStepTracker extends JobService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks{
public static final String JOB_TAG = BackgroundStepTracker.class.getName();
private GoogleApiClient mClient = null;
public static final String TAG = "BACKGROUND";
private Context _context;
private SharedPreferences _sharedPreferences;
private static final String SHARED_PREFERENCES = "SHAREDPREFERENCES";
public BackgroundStepTracker(){
}
@Override
public void onCreate() {
super.onCreate();
_sharedPreferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
_context = getApplicationContext();
}
@Override
public boolean onStartJob(JobParameters job) {
Log.d(TAG, "Working");
mClient = new GoogleApiClient.Builder(_context)
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.build();
return false;
}
@Override
public boolean onStopJob(JobParameters job) {
Log.d(TAG, "Stopping");
return false;
}
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(mClient, DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.i(TAG, "Existing subscription for activity detected.");
} else {
Log.i(TAG, "Successfully subscribed!");
}
} else {
Log.w(TAG, "There was a problem subscribing.");
}
}
});
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs. What to do?
// Subscribe to some data sources!
subscribe();
}
@Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.w(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.w(TAG, "Connection lost. Reason: Service Disconnected");
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
答案 0 :(得分:2)
我的错误是在构建它之后没有调用mClient.connect()。这解决了我的问题。