Android Googleapiclient’s onConnect() обратный вызов никогда не вызывается

Я следую учебнику Google по получению местоположения в моем Android-приложении с помощьюGoogleApiClient, но я сталкиваюсь с проблемой после того, как я создаю клиент и пытаюсь подключиться. Я вижу, что клиент пытается подключиться, но onConnected()ни onConnectionFailed()один обратный вызов никогда не вызывается. Таким образом, клиент никогда не устанавливает соединение и не сообщает, что ему это не удалось. Чего мне здесь не хватает?

UPDATE: добавлена проверка разрешений для доступа к местоположению.

public class MainActivity extends AppCompatActivity
    implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

public static final String LOG_TAG = MainActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private final static int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 0;

private Location mCurrentLocation = new Location("default");
private GoogleApiClient mGoogleApiClient = null;
private Location mLastLocation = null;

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Log.e("Connected: ", String.valueOf(mGoogleApiClient.isConnected()));
                mGoogleApiClient.connect();
                Log.e("Connected: ", String.valueOf(mGoogleApiClient.isConnected()));

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // check if permissions are granted
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

    }

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}


@Override
protected void onStop() {
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }

    super.onStop();
}

private void handleNewLocation(Location location) {
    Log.d(LOG_TAG, location.toString());
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    try {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation == null) {

        }
        else {
            handleNewLocation(mLastLocation);
        }
    } catch (SecurityException e) {
        DialogFragment mlocationDialog = new LocationDialogFragment();
        mlocationDialog.show(getSupportFragmentManager(), "locationDialog");
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i(LOG_TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

1 ответ

  1. Вы реализовали разрешения ??

    @Override
    public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
        switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
    
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    
        // other 'case' lines to check for other
        // permissions this app might request
    }
    }
    

    Подробнее : https://developer.android.com/training/permissions/requesting.html