Can GoogleApiClient be used in Fragment or should it always be used in Control?

Can GoogleApiClient be used in Fragment or should it always be used in Activity

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

      

+3


source to share


2 answers


GoogleApiClient

can work in Activity

, Fragment

or Service

. It requires it Context

, and you can get it getApplicationContext()

, getActivity()

etc. Yours Fragment/Activity

should implement these two interfaces:

implements
ConnectionCallbacks, OnConnectionFailedListener

      

then you will find the following methods:



@Override
public void onConnected(Bundle bundle) { 

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

      

You need to connect this API client using this mGoogleApiClient.connect();

and disconnect viamGoogleApiClient.disconnect()

Here's the documentation for accessing Google APIs. Here's a description. And this thread has my working Demo code.

+10


source


Yes, you can use it inside a fragment. You just need to provide the Context to the builder (which you can use getActivity()

for) and let the Fragment implement the required interfaces.



new GoogleApiClient.Builder(getActivity())
...

      

+5


source







All Articles