I'm making an app that requires steps to be counted in the background. In a JobService class I'd like to connect to the GoogleFit API and read the steps. The issue I'm having is I can't get GoogleFit to connect. My log "Working" shows, but none of the logs for the Fit connections appear, which leads me to believe the connection is never happening. I tried starting the client builder in onCreate() and onStartJob(), neither worked. Any ideas?
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) {
}
}
My mistake was not calling mClient.connect() after building it. This solved my issue.