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

前端 未结 2 1136
长发绾君心
长发绾君心 2021-01-20 18:38

I looked at this Q&A here: GoogleApiClient is throwing "GoogleApiClient is not connected yet" AFTER onConnected function getting called

As it seemed to

相关标签:
2条回答
  • 2021-01-20 19:06

    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();
    }
    
    0 讨论(0)
  • 2021-01-20 19:08
    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

    0 讨论(0)
提交回复
热议问题