Using GoogleApiClient in a service

RHL picture RHL · Apr 18, 2015 · Viewed 9k times · Source

I am trying to get location update information in service. For this I have created a service and in onStartCommand of service class I am creating GoogleApiClient, but I am not getting connection call back in the service. Please help to resolve this.

Below given is the service code and in activity I have started service using startService method :

startService(new Intent(this, LocationService.class));

service code

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
                    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleApiClient mLocationClient;

private Location mCurrentLocation;
LocationRequest mLocationRequest;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO do something useful
    Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
    mLocationClient = new GoogleApiClient.Builder(LocationService.this)
    .addApi(LocationServices.API).addConnectionCallbacks(LocationService.this)
    .addOnConnectionFailedListener(LocationService.this).build();

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mLocationRequest.setFastestInterval(1000);
    return Service.START_NOT_STICKY;
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    mCurrentLocation = location;
    Toast.makeText(this, mCurrentLocation.getLatitude() +", "+ mCurrentLocation.getLatitude(), Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    //if(servicesConnected()) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
    //}

}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "Disconnected. Please re-connect.",
            Toast.LENGTH_SHORT).show();
}



@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

Answer

ianhanniballake picture ianhanniballake · Apr 18, 2015

The main issue: you never call mLocationClient.connect() so the connection process never starts.

Also, onStartService() can be called multiple times (i.e., every time startService() is called - instead, you should move this to onCreate() for your Service to ensure it is only called once during the lifecycle of your Service. Similarly, you should removeLocationUpdates() in onDestroy() and disconnect your mLocationClient.