Reputation: 1042
I'm registering my app after boot to receive location updates. My boot receiver is starting a service that does the initialization:
@Override
protected void onHandleIntent(Intent intent) {
GoogleApiClient client = _googleApiBuilder.get()
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
Sometimes in the onConnected
callback method I'm getting exception indication I'm not connected yet. After some research I've encountered this - GoogleApiClient is throwing "GoogleApiClient is not connected yet" AFTER onConnected function getting called
It made me think, does the way I'm initializing google api is correct ? e.g. should I initialize it in a service ?
What is the suggested way to do it in the background ?
Upvotes: 1
Views: 228
Reputation: 1042
Used the following solution instead:
googleApiInstance.blockingConnect(10, TimeUnit.SECONDS);
or in other words instead of running the operation in a different thread (that's what connect
is doing), I'm running it in my own thread (I'm using IntentService
) and manage the connection life cycle on my own.
Upvotes: 0
Reputation: 676
Hope it will be helpful to you.
public class LocationService extends Service implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
private static final String TAG = LocationService.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initGoogleApi();
}
@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onLocationChanged(final Location location) {
}
@Override
public void onConnectionFailed(final ConnectionResult result) {
}
@Override
public void onConnected(final Bundle bundale) {
createLocationRequest();
}
@Override
public void onConnectionSuspended(final int arg0) {
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
protected void createLocationRequest() {
final LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(Constants.INTERVAL);
mLocationRequest.setFastestInterval(Constants.FAST_INTERVAL);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(0);
startLocationUpdates(mLocationRequest);
}
private void initGoogleApi() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
}
Upvotes: 0