Tutorial: Integrating Google Play Services with LibGDX

Source Code for tutorial on Github

Over the past week I have been working on adding online leader boards to my game FlyBy using the Google Play Services game API’s. As I ran into a few things that caught me out I thought I would write up how I got it working in hope it helps other people. So here we go:

Prerequisites

  • a Google developer account (this requires paying the $25 registration fee)

It is probably a good idea to have downloaded and got the Type-A-Number example from the Google developer site (which you can find here) working before you try integrating with LibGDX just to make sure you know how to handle the backend stuff on the website like setting up an OAuth 2.0 client ID and linking it to your app (which isn’t as hard as it may sound!). I’d highly recommend following that tutorial before this one. Some things to watch out for on Type-A-Number tutorial:

  • BaseGameUtils doesn’t import as a library, have to click the toggle box “isLibrary” on the projects properties (right click BaseGameUtils go to Properties>Android and tick the “isLibrary” box)
  • If you get “NoClassDefFoundErorr” when trying to run the project make sure to go the android projects properties > Java Build Path and make sure to tick the check box’s next to the dependencies your project uses.
  • Logging in with my developer account in game didn’t work for me, even with it set to be a tester (which happened automatically). If you are getting “Unknown Error” when attempting to sign in try using a different Gmail account (Be sure to add the account as a tester)

LibGDX Intergration

If you have got the Type-A-Number tutorial running your in a pretty good position, theres only a few changes needed to make it work with LibGDX. You can get the source code for this tutorial here. This tutorial assumes you are using Eclipse.

Step 1 - Import BaseGameUtils and google_play_services_lib into your LibGDX project.

  • The BaseGameUtils project is located from the Google Play Game Services Sample Games located here. It also came with the Type-A-Number tutorial so you can just grab it from there too.
  • google_play_services_lib is located in your android SDK folder at android-sdk\extras\google\google_play_services

To import the projects go to file>import>android>Existing Android Code into Workspace. Browse to the location of the lib your importing. The project should show up in the “Project to import” section. Make sure to click copy projects into workspace. Do this for both projects.

Step 2 - Add google_play_services_lib as a dependency for BaseGameUtils.

  • To do this right click BaseGameUtils and then click properties>Jave Build Path>Project>Add . In the popup box tick the google_player_services_lib and click ok. This should remove the errors BaseGameUtil was complaining about. If not try Project>Clean and hopefully that will help.

Step 3 - Add google_play_services_lib and BaseGameUtils as build dependencies for your Android project. To do this:

  • Make sure BaseGameUtils is set to “isLibrary” to do this right click BaseGameUtils go to Properties>Android and tick the “isLibrary” box.
  • Now add them to your Android project. Right click your Android project and go to Properties>Android in the library section click add and add both projects. They should appear in the pop up window after clicking add.
How it should look

How it should look

  • Right click your Android project and go to Properties>Java Build Path>Order and Export and make sure to tick the box next to ‘Android <your android version>’ and ‘Android Private Libraries’ as well as any others your project relies on (this is required for the newer Android Developer Tools).
How it should look

How it should look

At this point the game should compile and deploy to a device without any errors. We can now begin working on the code. We need need to set-up some interfaces for platform specific code. We will pretty much just be doing what is discussed on this page. But to begin with we will setup a xml file to hold some important values needed by Google Play Services.

Step 4 - Setup an xml file to hold values for the application id (that you get from your google developer page). The advantage of using an xml file like this means you don’t have to change the value throughout your project, just one place you put the value in and reference it from there everywhere else in your project

  • In your Android project go to res>values and create a new xml file (right click values folder> new> Android XML File and call it ids.xml then click finish. Either click the add button and create a new String. When the string is created name it  ’app_id’ and give it the value of your games ID from the Google developer page for your game or edit the file directory in the text editor by clicking the ‘ids.xml’ tab at the bottom.
  • Open your AndroidManifest.xml file and click the ‘AndroidManifest.xml’ tab at the bottom to get the text editor. We need to add some code to setup the ‘ids.xml’ to work so add the following code inside your ‘application’ tag. I have it under android:label

PasteBin Version of Code with better formatting

<meta-data android:name="com.google.android.gms.games.APP_ID"
            android:value="@string/app_id" />

PasteBin Version of Code with better formatting
Step 5 – Create the base interface for platform specific code

  • Go to your main LibGDX project and create a new interface. I called it GoogleInterface. I set-up a very basic interface for this tutorial that has some very basic wrapping of some Google Play Services functions. You will most likely need to expand on this or create your own. But mine looks like the following:

PasteBin Version of Code with better formatting

package com.me.gdxGooglePlay;

public interface GoogleInterface {

public void Login();
public void LogOut();

//get if client is signed in to Google+
public boolean getSignedIn();

//submit a score to a leaderboard
public void submitScore(int score);

//gets the scores and displays them threw googles default widget
public void getScores();

//gets the score and gives access to the raw score data
public void getScoresData();
}

PasteBin Version of Code with better formatting

Step 6 - Create a class that implements the GoogleInterface for the Desktop implementation

  • Still in the main LibGDX project create a new class, I called it DesktopInterface and let it implement the GoogleInterface. My version of this class looks like the following:

PasteBin Version of Code with better formatting

package com.me.gdxGooglePlay;

public class DesktopInterface implements GoogleInterface{

@Override
public void Login() {
System.out.println("Desktop: would of logged in here");
}

@Override
public void LogOut() {
System.out.println("Desktop: would of logged out here");
}

@Override
public boolean getSignedIn() {
System.out.println("Desktop: getSignIn()");
return false;
}

public void submitScore(int score){
System.out.println("Desktop: submitScore: " +score);
}

@Override
public void getScores() {
System.out.println("Desktop: getScores()");
}

@Override
public void getScoresData() {
System.out.println("Desktop: getScoresData()");
}
}

PasteBin Version of Code with better formatting

Step 7 - In your projects main game class (the one that extends from ApplicationListener) create a constructor that takes an instance of GoogleInterface as a parameter. My constructor looks like this:

public Game(GoogleInterface aInterface){
platformInterface = aInterface;

platformInterface.Login();
}

As you can see I store the interface in this class, what you do with it once its in the project is up to you. I also call the interfaces Login method straight away so the game attemps to Login when it starts. In practice this probably isn’t a good idea. But for testing its fine.

Step 8 - Change MainActivity in your android project to implement GoogleInterface.

  • There is a lot going on at this stage. You need to make your MainActivity implement both GoogleInterface and GameHelperListener. This class will handle most of the actual talking with BaseGameUtils. I’ve set up a basic implementation that handles logging in, logging out, submitting and receiving scores. It probably isn’t suited to go straight into a game but demonstrates some ways to do these tasks. The main thing to note here is you pass the MainActivity into the Game constructor. Here is my class:

Pastebin version of code

If your getting an error with leaderBoardID you need to add it to your strings.xml file which is located in your Android project at res>values>strings.xml. The value for leaderBoardID should be the value of a leader board from your Google Developers page if you have made a leaderboard for the project.

At this point running the game should prompt you to choose a google account to log in with. If that actually happened, I’m surprised! If it didn’t, I probably forgot something or the tutorial needs to be more clear, so please contact me where you have got lost or what’s going wrong and I will try to help!

Source Code for tutorial on Github

25 comments to Tutorial: Integrating Google Play Services with LibGDX

  1. Spide says:

    Hi, i have little problem … after step “Right click your Android project and go to Properties>Java Build Path>Order and Export and make sure to tick the box next to ‘Android ’ and ‘Android Private Libraries’”

    I cant run my android project… this is error:

    [2013-06-11 20:59:02 - Dex Loader] Unable to execute dex: Multiple dex files define Laurelienribon/bodyeditor/BodyEditorLoader$CircleModel;
    [2013-06-11 20:59:02 - archeryJam-android] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Laurelienribon/bodyeditor/BodyEditorLoader$CircleModel;

    Thank for reply

    • admin says:

      Hi Spide,

      Are you using the newest version of ADT? I am not sure after what version but at some point the way you include dependencies changed. If you are using an older version of ADT you may not need to do that step! Have you tried compiling it without ticking the box next to them?

      Thanks,
      Nathan

      • Spide says:

        Hi,

        i tried a lot of thinks, update everything, checkt all dependencies and others.
        But i fix it when i created new project and copy all files from old to new project.
        I dont know what was wrong but it works now.

  2. Spide says:

    Hi,

    i tried a lot of thinks, update everything, checkt all dependencies and others.
    But i fix it when i created new project and copy all files from old to new project.
    I dont know what was wrong but it works now.

  3. Kyle says:

    Great tutorial. I was able to add everything. However, I wanted to know if you hit this one problem.

    When the game loads, it brings me to google,and a white screen pops up asking me if I want to use the services. I click accept, and the white box doesn’t go away. I just get the processing circle. I figured it would go away.

    • Nathisgreen says:

      Did it work the first time you logged in? The only thing I can think is to try logging in with a different gmail account to the one that is linked to your developer panel. I had a similar issue and it worked once I did that. No idea why it didn’t work with my original account.

      • SpokDev says:

        Thanks for the tutorial.
        But i am having the same issue.
        Googles example(Type-a-number) and one game from google play works like charm.
        But in my example I managed to login but had some issues. Now I even cant login – get white screen with moving circle.

  4. Turan says:

    Great tutorial.This helped a lot.

    How can i implement multiplayer functionality?It has some listeners and i have to invoke some methods of main libgdx project from android project.How can i do that?

  5. Andrews says:

    thanks for the tutorial.
    how to implement the gwt?

    • Nathisgreen says:

      The process to support gwt would be pretty similar coding wise as far as I am aware. You will just need to make an Interface for the gwt implementation of the Google play service functions just like this tutorial does for the android version. However setting up the certificate on the developer panel would be a little different. I believe there is a setting for web application during the set-up, but you would have to look into this yourself.

      Hope this helps!

  6. Marek says:

    Hi, thanks for the tutorial! All works until i use “initialize(new Game(this), cfg);” in -android project. When i pass Game(null) all working fine but when trying to pass “this” the game doesn’t start and crash with NullPointerException :/
    Any idea?

  7. Ross says:

    Works great. What have you found as the best way to get around the fact that the Export KeyStore used is different than the one when doing normal testing/debugging?

    • Nathisgreen says:

      I haven’t really done much packaging and exporting of my app so cannot recommend any best practices for that. If you have found any good tips for the issue please share :-)

    • jason says:

      I’ve just been setting up two linked app entries – both going to the same app but setup as separate Oauth clients using the two different keys.

      But I’m also having a problem with “unknown error” pop-ups after logging in. I’m still getting logged in and everything seems to be working – but can’t figure out what’s causing the errors. It happens with my dev account, a separate testing account I created and added as a tester and friends who I’ve added as testers.

      I’ve seen lots of similar reports on stackexchange with similar errors and they were all due to problems with the app_id being wrong or the Oauth stuff not being setup right…but in all of those cases people weren’t able to login and use the services. Since I can login and use the services I’m not convinced it’s an authentication issue I’m experiencing.

      • Jason says:

        Just wanted to update that I took another look at my project over the weekend and saw that baseGameUtils has been updated on github so I pulled the updated gameHelper down and the problems I was having with error messages after successful logins went away.

        The updates on github were from 18 days ago so shortly after I posted that last comment.

        I’m still having some problems switching from my game to the leaderboard/achievements displays…but I’m 99% sure that’s my fault and not the base library.

  8. Jason says:

    Thanks for the tutorial, helped bring all the pieces together for me. Biggest problem I had was I accidentally put the APP_ID tag in my inside the in my Manifest. The errors that caused seemed really non-obvious…but eventually I realized what was wrong and after moving my APP_ID out of the it worked!

    Now the real fun of actually implementing the actual functions!

  9. Thanks for the tutorial! I think “Google Play Services” can still improve a bit, but as will all games include support for it.

  10. Hello,
    Thanks for the tutorial! All works fine!

  11. Nicte says:

    Hey! First of all, thanks for the tutorial! Really helped out!

    Just one question, following your tutorial, my libgdx game now shows the title bar and I get this on the console:

    10-02 20:48:07.490: I/AndroidApplication(11150): Content already displayed, cannot request FEATURE_NO_TITLE

    How did you solve this?

    Thanks again!
    Nicte

    • Nicte says:

      Sorry! I hate when I ask too soon! :P

      Solution: Add this on the onCreate() method:

      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    • Boive says:

      The problem comes from the
      aHelper.setup(this);
      that should be done after the “initialyze” in the onCreate method.
      Thx for the tuto btw !

  12. Julien says:

    Hi and thanks for the tutorial !
    I managed to get everything working, I have my login screen but when I try to login I get a message saying that the application is incorrectly configured.
    I checked the package name and the id displayed in tomcat for debugging and it matches the one in the developer console.
    I tried 3 differents google account each added to the beta test. I also tried to add the app another time, same result.
    I notice that the SHA1 differ if I compile the apk or just launch it from eclipse but none of them works :/
    Did some had the same problem ?

  13. mohit says:

    hi…
    i work on a project in cocos2dx for android,
    i will try above instruction but it can’t work,
    than if you have some time please make a demo project
    and upload is on this blog asa possible. thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>