GoogleApiClient is not connected yet, even though onConnected is called and I'm creating my GoogleApiClient in onCreate

╄→гoц情女王★ 提交于 2019-12-01 21:20:27

Your problem is in the onResume logic:

@Override
protected void onResume() {
    super.onResume();
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }

    resumeLocationUpdates();

}
private void resumeLocationUpdates() {
    Log.i("RESUMING", "RESUMING LOCATION UPDATES");
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
}

The call to mGoogleApiClient.connect() is asynchronous. It returns before the connect is finished, and you are requesting location updates before the client is connected. You need to move the requestLocationUpdates call to the GoogleApiClient.onConnected callback. After this event, your client is connected.

@Override
protected void onResume() {
    super.onResume();
    if (!mGoogleApiClient.isConnected()) {
        mGoogleApiClient.connect();
    }   
}

@Override
public void onConnected(Bundle bundle) {
    resumeLocationUpdates();
}
Gowtham Chandrasekaran
  1. Your class must implement GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener and override all the methods.

  2. GoogleApiClient will communicate with the LocationServices and give you the users latitude and longitude.

  3. In your OnCreate() method build a GoogleApiClient that uses the desired api.

  4. In your onStart() method start connecting the GoogleApiClient.

  5. On the Sucessfull connection OnConnected() method is called where we will be making our LocationRequest.

  6. Once we make the request onLocationChanged() method is called where we will be using the location object to get the latitude and longitude updates continuously.
  7. onConnectionSuspended(), onConnectionFailed() will be used when the connection is suspended and the connection is failed.
  8. Dont forget to disconect the GoogleApiClient connection in onStop() method else lot of resources will be wasted.

Watch here for tutorial Android Location API Using Google Play Services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!