Android的GoogleApiClient onConnect()回调永远不会被调用

时间:2016-11-07 14:24:55

标签: android android-googleapiclient

我正在关注使用GoogleApiClient在我的Android应用中获取位置的Google教程,但在构建客户端并尝试连接后,我遇到了一个问题。我看到客户端尝试连接,但是onConnected()onConnectionFailed()回调都没有被调用。因此,客户端从不建立连接或报告他没有这样做。我在这里缺少什么?

更新:添加了访问位置的权限检查。

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 个答案:

答案 0 :(得分:0)

您是否实施了权限?

@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