3

Can GoogleApiClient be used in a Fragment or must it be always used in a Activity

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
chiwangc
  • 3,566
  • 16
  • 26
  • 32
kcube
  • 47
  • 1
  • 3

2 Answers2

10

GoogleApiClient can work in Activity, Fragment or Service. It needs a Context and you can get it by getApplicationContext() , getActivity() etc. Your Fragment/Activity has to implement these two interfaces:

implements
ConnectionCallbacks, OnConnectionFailedListener

then you will find these methods:

@Override
public void onConnected(Bundle bundle) { 

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

You have to connect this API client using this mGoogleApiClient.connect(); and disconnect via mGoogleApiClient.disconnect()

Here is the documentation about Accessing Google APIs. Here is the description. And this thread has my Demo working code.

Community
  • 1
  • 1
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
  • 2
    When used in a fragment, `getActivity()` will not work until Callbacks are implemented by the activity holding the fragment. Rather, `fragment_name.this` or `this` would be the right way to get the context in a fragment and fragment has to implement the callbacks – Hanu May 18 '17 at 13:34
5

Yes you can use it within a Fragment. You just have to provide a Context to the builder (which you can use getActivity() for) and let the Fragment implement the required interfaces.

new GoogleApiClient.Builder(getActivity())
...
Floern
  • 33,559
  • 24
  • 104
  • 119