Click here to see your recently viewed pages and most viewed pages.
Hide
Google Play Game Services

Accessing the Games APIs

Before your game can make any calls to the Play Game services, it must first establish an asynchronous connection with the Google Play servers by using an GoogleApiClient object and authenticating the user with the Play Game services.

Setting up your game project

To simplify your coding, use the methods proviced in the BaseGameUtils library to resolve connection errors and display error dialogs. You can download this library from the Downloads page.

To import the BaseGameUtils library and link it to your game project in Android Studio:

  1. Open your game project in Android Studio. If you haven't installed Android Studio, get the latest version from the official downloads site.
  2. Click File > Import Module and navigate to the directory on your machine where you downloaded android-basic-samples. Select the BaseGameUtils module in the BasicSamples/libraries directory. Click OK.
  3. Modify the dependencies in the build.gradle file for the module that will use BaseGameUtils:

    dependencies {
        compile project(':BaseGameUtils')
        // ...
    }
    

  4. Build the project by clicking Build > Make Project.

In your main game activity, import the com.google.android.gms package and the BaseGameUtils class. In your Activity, implement the GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener interfaces.

import com.google.android.gms.*;
import com.google.example.games.basegameutils.BaseGameUtils;

public class MyGameActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

To see how to implement user sign-in from your main activity, see Implementing Sign-in on Android.

Obtaining the Google Api Client and Connecting

Your game must have a reference to the GoogleApiClient object in order to make any API calls to the Play Game services. Create the GoogleApiClient object in onCreate() using the GoogleApiClient.Builder class. For example:

private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create the Google Api Client with access to the Play Game services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            // add other APIs and scopes here as needed
            .build();

    // ...
}

In order for your game to communicate with Play Game services, your client must first establish a connection. You can disconnect the client once your game no longer needs access to these services. Connect the mGoogleApiClient in onStart() and disconnect it in onStop():

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

Implement onConnected() to be notified when sign-in is successful:

@Override
public void onConnected(Bundle connectionHint) {
    // The player is signed in. Hide the sign-in button and allow the
    // player to proceed.
}

Next, implement onConnectionFailed() and onConnectionSuspended():

private static int RC_SIGN_IN = 9001;

private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (mResolvingConnectionFailure) {
        // already resolving
        return;
    }

    // if the sign-in button was clicked or if auto sign-in is enabled,
    // launch the sign-in flow
    if (mSignInClicked || mAutoStartSignInFlow) {
        mAutoStartSignInFlow = false;
        mSignInClicked = false;
        mResolvingConnectionFailure = true;

        // Attempt to resolve the connection failure using BaseGameUtils.
        // The R.string.signin_other_error value should reference a generic
        // error string in your strings.xml file, such as "There was
        // an issue with sign-in, please try again later."
        if (!BaseGameUtils.resolveConnectionFailure(this,
                mGoogleApiClient, connectionResult,
                RC_SIGN_IN, R.string.signin_other_error)) {
            mResolvingConnectionFailure = false;
        }
    }

    // Put code here to display the sign-in button
}

@Override
public void onConnectionSuspended(int i) {
    // Attempt to reconnect
    mGoogleApiClient.connect();
}

Implement onActivityResult() to handle the result of the connection resolution:

protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        mSignInClicked = false;
        mResolvingConnectionFailure = false;
        if (resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        } else {
            // Bring up an error dialog to alert the user that sign-in
            // failed. The R.string.signin_failure should reference an error
            // string in your strings.xml file that tells the user they
            // could not be signed in, such as "Unable to sign in."
            BaseGameUtils.showActivityResultError(this,
                requestCode, resultCode, R.string.signin_failure);
        }
    }
}

Finally, add sign-in and sign-out buttons to your layout. Implement the following callbacks to notify your app when these buttons are clicked:

// Call when the sign-in button is clicked
private void signInClicked() {
    mSignInClicked = true;
    mGoogleApiClient.connect();
}

// Call when the sign-out button is clicked
private void signOutclicked() {
    mSignInClicked = false;
    Games.signOut(mGoogleApiClient);
}

Accessing additional Google Play services APIs

The code above only grants access to the Play Game services APIs. To add additional Google Play services APIs or scopes to the GoogleApiClient, add calls to addApi() and addScope when building the client in onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create the Google Api Client with access to the Play Game and Drive services.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            .addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER) // Drive API
            .build();

    // ...
}

Guarding API calls

You are strongly encouraged to guard calls to Play Game services API methods with a check to verify that the user is signed in. The following snippet shows how you can verify the user's sign-in status before unlocking an Achievement.

final static String MY_ACHIEVEMEMENT_ID = "...."; // your achievement ID here

if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
    // Call a Play Game services API method, for example:
    Achievements.unlock(mGoogleApiClient, MY_ACHIEVEMENT_ID);
} else {
    // Alternative implementation (or warn user that they must
    // sign in to use this feature)
}