Подтвердить что ты не робот

Использование GoogleApiClient в службе

Я пытаюсь получить информацию об обновлении местоположения. Для этого я создал службу, а в onStartCommand класса сервиса я создаю GoogleApiClient, но я не получаю звонок соединения в службе. Пожалуйста, помогите решить эту проблему.

Ниже приведен код службы и в действии я начал службу с использованием метода startService:

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

код службы

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;
}

}

4b9b3361

Ответ 1

Основная проблема: вы никогда не вызываете mLocationClient.connect(), поэтому процесс подключения никогда не запускается.

Кроме того, onStartService() можно вызывать несколько раз (т.е. каждый раз, когда вызывается startService()), вы должны переместить его на onCreate() для Service, чтобы убедиться, что он вызывается только один раз в течение жизненного цикла ваша служба. Аналогично, вы должны removeLocationUpdates() в onDestroy() и отключите mLocationClient.