• Stick Nodes - 100% Complete Go animate some stickfigures. Google Play links: [free] or [pro]. App Store links: [free] or [pro].
Oil Spill Escape
Stick Nodes

Get it from: App Store | Google Play | SlideMe | Amazon | Opera

Tutorial: Set up Google Services with LibGDX

77comments

If nothing else, Plunder Peril served as a great learning experience for myself in terms of understanding how to prepare for and launch a game on Google Play.

When finalizing the game, I finally reached that point where it was time to begin implementing an API for leaderboards, ads, and analytics-tracking.  I knew about Google Services for Android and intended on utilizing them from the beginning.  However, when it came time to actually get the API implemented, things began to get a bit confusing (it wasn’t just as simple as plugging in an ID number into your Flash game provided by the Mochi Media dashboard, that’s for sure).

So that’s why I’m writing this guide.  I know when I was putting all of this stuff together for the first time I had two incredibly helpful guides I referred to:

I figured I’d write my own tutorial as well to give a third perspective.  So let’s get started.

EDIT: Sorry about the lack of tab spacing in the code, WordPress is absolutley the worst to work with when it comes to posting code, their WYSIWYG editor loves to change things up on you but it’s too useful to just disable completely.  The code will still work, of course, you just have to tab it yourself, sorry!

Step 1 – Download the things

You need two specific things from Google to get started.

  1. Google Play Services SDK – Download through Eclipse ADT, follow these instructions.
  2. BaseGameUtils – Download from the list found here.

Step 2 – Set up the things in your workspace

Now you need to actually import these projects and put them on your build path.  Here’s how to do that.

(Ignore any errors that pop up while importing, they will hopefully be sorted out soon enough.)

For Google Play Services SDK:

  1. First, import the Google Play Services SDK. With Eclipse open to your current workspace, go to File > Import > Android > Existing Android Code Into Workspace.
  2. Browse to where the Google Play Services SDK is saved (when downloaded through Eclipse ADT, it is location at [Android SDK Location]\sdk\extras\google\google_play_services and select it.  Before importing, be sure to check Copy projects into workspace.

Google Play Services LibGDX

For BaseGameUtils:

  1. Again, first step is to import the project. With Eclipse open to your current workspace, go to File > Import > Android > Existing Android Code Into Workspace.
  2. Browse to where the BaseGameUtils project is saved and select it. Before importing, be sure to check Copy projects into workspace.
  3. After it is imported, right-click BaseGameUtils in the Package Explorer window and select Properties > Jave Build Path > Projects > Add and select google-play-services_lib.  This should resolve the errors produced by BaseGameUtils, if not, cleaning the project may help in Project > Clean.
  4. Right-click BaseGameUtils in the Package Explorer window again and select Properties > Android.  Here, make sure the isLibrary checkbox is checked.

Google Play Services LibGDX

Step 3 – Link the things to your Android project

Okay, now we have the two projects imported and set up in our workspace.  Time to actually intertwine them into our game.

Now, this tutorial is focused on setting up Google Services for LibGDX projects, so the steps from here on out may require tweaking if you’re not using LibGDX.

  1. Right-click your Android project and select Properties > Android.  Click Add and add both projects (google-play-services_lib and BaseGameUtils).
  2. Now, still in the Properties menu, go to Java Build Path > Order and Export.  From here, make sure the checkboxes next to Android X.X.X and Android Private Libraries is checked.

Step 4 – Modifying the Android Manifest

Now, before you continue any further, you should have a project for your game set up on your Google Play Developer Console.  I’m not going to go in depth into that process, but it’s pretty straightforward.  You need to go into the Game Services tab on the left, click on Add Game, fill out the information, and you’re done.  What you need is your app ID, which is specified next to the title of your game.

Google Play Services LibGDX

  1. First, we’re going to create a new XML file to hold our IDs.  In the Package Explorer window, go to your Android project > res folder > values folder.  Right click the folder and select New > Other > Android > Android XML File.  Call it ids.xml and save it.
  2. Grab the app ID of your game from your Google Play Developer Console and put the following inside of ids.xml (fill in your own app ID):
1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_id">YOUR APP ID HERE</string>
</resources>

Once you have this XML file created, we need to modify the Android Manifest file.

  1. Open the Android Manifest and add the following anywhere inside of the <application> tag:
1
2
<meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Alright! At this point, the Google Services SDK should be embedded into your game and will be able to “talk” to the Google Servers.  Next up, let’s actually make it do something.

Step 5 – Create the basic foundation

Alright, now we’re going to work with Java.

One thing I didn’t understand right away (since this was my first working with anything like this), was how you were going to be able to call Google Services API functions (built into the Android-side of things) from the source files of the game.  The answer was simple, an interface!

  1. In your source game files, create a new Java interface and call it IGoogleServices.
  2. Inside of this file, place the following code:
1
2
3
4
5
6
7
8
9
public interface IGoogleServices
{
public void signIn();
public void signOut();
public void rateGame();
public void submitScore(long score);
public void showScores();
public boolean isSignedIn();
}

I’m sure you can tell what we’re planning to implement just due to the names of the functions.  Once you are set up, you will be free to add/remove functions from this interface as you see fit, I just felt like these are a good starting point.

Anyway, since we have an interface, now we need some things to implement it.

  1. In your source game files, create a Java class and call it DesktopGoogleServices and have it implement the interface we just created, IGoogleServices.
  2. Inside of this file, place the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class DesktopGoogleServices implements IGoogleServices
{
@Override
public void signIn()
{
System.out.println("DesktopGoogleServies: signIn()");
}

@Override
public void signOut()
{
System.out.println("DesktopGoogleServies: signOut()");
}

@Override
public void rateGame()
{
System.out.println("DesktopGoogleServices: rateGame()");
}

@Override
public void submitScore(long score)
{
System.out.println("DesktopGoogleServies: submitScore(" + score + ")");
}

@Override
public void showScores()
{
System.out.println("DesktopGoogleServies: showScores()");
}

@Override
public boolean isSignedIn()
{
System.out.println("DesktopGoogleServies: isSignedIn()");
return false;
}
}

So what is this class’s purpose?  Well, since you can’t run the Google Services on anything other than an Android device, this will be the class the game uses when it’s running on the desktop.  It’s really doesn’t do anything other than fill the space where the real Google Service calls would be.

Step 6 – Properly set up your Android application

Okay, now we’re getting into the real stuff.  To begin, we’re going to start setting up MainActivity.java in our Android project.

  1. Open up MainActivity.java and have it implement IGoogleServices (have it keep extending AndroidApplication like it already should be – this is a main part where this tutorial is diverting from other tutorials, since you can’t just extend BaseGameActvity because you’re using LibGDX).  Because it’s implementing the IGoogleServices interface, you’re going to need to add in all of the functions it needs to override, go ahead and do that and just leave them empty for now.
  2. Create a new GameHelper member and call it _gameHelper.  In the onCreate() function, initialize it like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private GameHelper _gameHelper;

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

// Create the GameHelper.
_gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
_gameHelper.enableDebugLog(false);

GameHelperListener gameHelperListener = new GameHelper.GameHelperListener()
{
@Override
public void onSignInSucceeded()
{
}

@Override
public void onSignInFailed()
{
}
};

_gameHelper.setup(gameHelperListener);

// The rest of your onCreate() code here...
}

Next up, you need to notify the _gameHelper object of the state of the Android application.  To do this, you need to inform it of onStart(), onStop(), and onActivityResult() function calls.  It’s pretty simple, just add the following to MainActivity.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
protected void onStart()
{
super.onStart();
_gameHelper.onStart(this);
}

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
_gameHelper.onActivityResult(requestCode, resultCode, data);
}

If we had just extended BaseGameActivity, all of the above would essentially be taken care of for us.  But like I said, we can’t do that, so we have to do it manually.  In the end it really isn’t a big deal, now is it?

Alright, now comes the next step.  We need to pass the MainActivity class to our main game class – this is how we’re going to call all of those functions we defined in the IGoogleServices interface.

  1. In MainActivity.java, find the line of code where you initialize your main game class, mine looks like this:
    1
    initialize(new Game(), cfg);
  2. Change it to the following:
    1
    initialize(new Game(this), cfg);
  3. Go into your desktop project and into Main.java, find the line where you initialize your main game class, mine looks like this:
    1
    new LwjglApplication(new Game(), cfg);
  4. Change it to the following:
    1
    new LwjglApplication(new Game(new DesktopGoogleServices()), cfg);
  5. Now both our desktop and Android projects are passing an instance of an IGoogleServices object to our main game class.  Let’s catch this object and store it as a static member so we can reference it all throughout our game files with no hassle.  In your main game class have something like the following, where you catch and store the IGoogleServices object:
1
2
3
4
5
6
7
public static IGoogleServices googleServices;

public Game(IGoogleServices googleServices)
{
super();
Game.googleServices = googleServices;
}

We’re done setting things up, now lets actually call some API functions.

Step 7 – Call all kinds of functions, all kinds

The following part of the tutorial actually fills in all of those blank interface functions in MainActivity.java.  Now, if you want to implement leaderboards, you’re going to need to create a leaderboard on your Google Play Developer Console.  Once it’s created, take the leaderboard ID and go into that ids.xml file we created and add it there:

1
<string name="leaderboard_id">YOUR LEADERBOARD ID HERE</string>

This is of course only if you want leaderboards.  Once this is done, it’s time to continue forward.

Alright, let’s fill in those blank functions in MainActivity.java.  Here’s the code for that (again, really sorry about the lack of tabbing, blame WordPress!):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@Override
public void signIn()
{
try
{
runOnUiThread(new Runnable()
{
//@Override
public void run()
{
_gameHelper.beginUserInitiatedSignIn();
}
});
}
catch (Exception e)
{
Gdx.app.log("MainActivity", "Log in failed: " + e.getMessage() + ".");
}
}

@Override
public void signOut()
{
try
{
runOnUiThread(new Runnable()
{
//@Override
public void run()
{
_gameHelper.signOut();
}
});
}
catch (Exception e)
{
Gdx.app.log("MainActivity", "Log out failed: " + e.getMessage() + ".");
}
}

@Override
public void rateGame()
{
// Replace the end of the URL with the package of your game
String str ="https://play.google.com/store/apps/details?id=org.fortheloss.plunderperil";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));
}

@Override
public void submitScore(long score)
{
if (isSignedIn() == true)
{
Games.Leaderboards.submitScore(_gameHelper.getApiClient(), getString(R.string.leaderboard_id), score);
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(_gameHelper.getApiClient(), getString(R.string.leaderboard_id)), REQUEST_CODE_UNUSED);
}
else
{
// Maybe sign in here then redirect to submitting score?
}
}

@Override
public void showScores()
{
if (isSignedIn() == true)
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(_gameHelper.getApiClient(), getString(R.string.leaderboard_id)), REQUEST_CODE_UNUSED);
else
{
// Maybe sign in here then redirect to showing scores?
}
}

@Override
public boolean isSignedIn()
{
return _gameHelper.isSignedIn();
}

And that’s pretty much the end of that!

Oh, and the REQUEST_CODE_UNUSED mentioned in the above code is just an integer, the value doesn’t really matter since it’s unused.  At the top of MainActivity.java I have a member:

1
private final static int REQUEST_CODE_UNUSED = 9002;

Your game will now start – if it’s on the Desktop it gets passed a new DesktopGoogleServices object (which really does nothing) and if it’s on an Android device it gets passed the MainActivity object.  Either way, both of these objects are IGoogleServices interfaces and thus can be used to call the different functions, signIn(), submitScore(), showScores(), etc from your main game source code.

Feel free to begin adding/removing your own functions to IGoogleServices.  Add things like achievements, multiplayer actions, more leaderboards, etc…

Signing your application

But wait!  You need to sign your Android application and give the SHA1 fingerprint to Google so it can link your API calls to your game (on your Google Play Developer Console, go to Game Services > select your game > Linked Apps > link an Android app and fill in all of the information > here you’ll be prompted for your SHA1 fingerprint).

A big issue I had was that I never found a clear, concise answer as to what exactly signing your application meant and how to do it.  Oh, and how to get your signing certificate fingerprint, otherwise known as the SHA1, which is required to use Google Services leaderboards.  If you’re in that boat, hopefully I can help clear things up for you.

Okay, so in simple terms, what does “signing your application” mean?  When your application is compiled, it is signed with a keystore file.  Every time you run/debug your Android application from Eclipse, Eclipse uses the same debug keystore to sign your application, it is located in the /.android/ folder on your C: (or in my case, my D:).

This is only used for debugging, though.  When you release your application you need to use your own keystore (more on that in a minute).  In the meantime, however, the debug keystore is still a keystore, and as a result you can still retrieve the SHA1 fingerprint from it and use that in your Google Play Developer Console (though when you eventually export a release build of the app with your own keystore, you’re going to need to use that SHA1 fingerprint from that keystore instead.)

To get the SHA1 fingerprint from the debug keystore in Eclipse, go to Window > Preferences > Android > Build.  There you’ll see the location of your debug keystore as well as the MD5 and SHA1 fingerprints.

Creating your own keystore

Okay, so you want to export a release-version of your Android application.  Here’s how to do it.

  1. Right-click your Android project in the Package Explorer window.  From here, select Android Tools > Export Signed Application package.
  2. In this window, your Android project should already be selected, so click Next.
  3. Now, if you already have a keystore created, browse to its location and fill in the password for it.  If you don’t have a keystore created, select Create new keystore and fill in a location to save it to as well as a secure password.
  4. On this next window, fill out an alias (use your first name), another password, the longevity of the certificate in years (choose a high number), and at least one of the other fields.
  5. That’s it, the keystore was created.  The window you are prompted with now is the window you’ll always see when you export a signed application – just choose where you want the APK to be saved and click Finish.

Google Play Services LibGDX

You can use that keystore you just created with all of your apps.  It is used to identify yourself as the legitimate app creator, so be careful with it.  Without that keystore, you won’t be able to sign an application the same way and as a result, updating your app once released on Google Play will be a bit of a hassle.

Things I learned / Having problems?

  1. In the tutorials I was reading, I don’t ever recall seeing the requirement to put this line in the Android Manifest:
    1
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

    However, it is required and led to a good headache until I figured it out.  Don’t forget it!

  2. To publish your app on Google Play using Google Services, you need to have at least 5 achievements in your game.  I wasn’t planning on achievements and couldn’t believe this was a requirement.  However, there’s a way around it.  Simply create 5 blank achievements on the Google Play Developer Console but don’t actually implement anything about them in your game.  And just like that, boom, you’re done.
  3. The first time I went to export a signed Android application, I was greeted with an error, something along the lines of:

    Plunder Peril is not translated in af, am, ar, be, bg, … (and essentially every other language in the world)

    This seemed a bit excessive, the solution is to turn this issue into a Warning, not an Error.  To do this, go to Window > Preferences > Android > Lint Error Checking and find the MissingTranslation ID and set it to Warning.

  4. I didn’t like Google Services immediately prompting me to log in as soon as my app started.  While you may want this functionality, it can be removed by simply adding the following in MainActivity.java:
    1
    _gameHelper.setMaxAutoSignInAttempts(0);

    Right before this code:

    1
    _gameHelper.setup(gameHelperListener);
  5. This is a bit of a weird one.  When I first exported my Android application as a release build, I needed to add a new linked app with a new SHA1 fingerprint to my Google Play Developer Console.  Even though I did this, and I made 100% sure that the SHA1 fingerprint was correct, my leaderboards wouldn’t work on my release build.  I eventually tracked down the solution – you need to actually publish the game services (not the actual application).  From the Google Play Developer Console, go to the Game Services tab, select your app, and in the drop-down bar on the right, select Publish Game.

The end

Wow, this is a long post.  Hopefully I didn’t miss anything.

If you have any questions, please post them in the comments!

  1. Umz utters: March 25, 2014 at 6:33 am

    You legend. You absolute legend.

  2. Waska blathers: April 2, 2014 at 4:53 pm

    Excuse me, but where you can download your entire working example?

    • Ralph states: April 2, 2014 at 4:56 pm

      Sorry, I don’t actually have one, I was basing this off of a larger project and never actually built a small stand-alone example.

  3. super apper announces: July 29, 2014 at 12:21 pm

    Hi. Great article thank you! I have finally got leaderboard working in my game thanks to you. One issue I have found is that whenever I submit a site, this shows the leaderboard, which is quite annoying. Can this be suppressed somehow?

    • Ralph says: July 29, 2014 at 12:59 pm

      I’m assuming you mean the leaderboard shows whenever you submit a score? It’s been a while since I’ve messed with the leaderboard stuff, but here’s the code directly from my game I use to submit a score, if it helps:

      1
      2
      3
      Games.Leaderboards.submitScore(_gameHelper.getApiClient(), getString(R.string.leaderboard_id), score);
      if (showScoresAfterSubmission == true)
      startActivityForResult(Games.Leaderboards.getLeaderboardIntent(_gameHelper.getApiClient(), getString(R.string.leaderboard_id)), REQUEST_CODE_UNUSED);

      It’s in a function that submits the score, and if a parameter “showScoresAfterSubmission” is true, it then shows the leaderboard.

      • super apper proclaims: July 29, 2014 at 3:38 pm

        Awesome, thank you! I will try that.

  4. Maximus blathers: August 21, 2014 at 7:34 pm

    Hey man when you said you have to publish the game on the developer console do you also have to upload the apk as a beta test in the application section of the console also? My logcat is giving me an error saying the id of my game is not linked to the package and this is my best guess as to why it’s not working.

    • Ralph blathers: August 21, 2014 at 7:40 pm

      Hey Maximus.

      I’m sure you’ve already tried this, but I’d google around for the exact error you’re receiving in the logcat.

      It’s been a while since I’ve did this stuff but I know I didn’t mess with alpha/beta stuff in the Google Play console. I’m not sure but I also don’t think I actually uploaded an apk until I was completely done with the app and was about to release it.

      • Maximus remarks: August 22, 2014 at 7:57 am

        Thanks for the quick response. I’m been looking for the problem and I think I might have discovered it. I havn’t got access to my normal computer at the minute so I can’t test it but I think it’s because the package name I was using in google play developer console was “com.website.game” when it should the same but with .android at the end. Do you remember if you added .android to the end of your package name?

        Also I recognised the game linked at the top of your site from the libgdx subreddit. I’ll have to check it out, sounds pretty cool!

        • Ralph says: August 22, 2014 at 8:04 am

          Well, all I know is that the package name identified in your Android manifest has to perfectly match the package name you input into the developer console (as in, don’t add .android if it’s not a part of the package name as described in the Android manifest).

          When you have a chance, if you want, post the error you’re receiving so I can get a better idea of what’s going on.

          Also, thanks!

  5. Kyle utters: September 1, 2014 at 3:39 am

    Hi, first off excellent tutorial! Describes everything perfectly.

    However, I’ve managed to screw something up… The problem is when I try to sign into Google Play Services I get a error dialog saying “Failed to sign in. Please check your network connection and try again.” This is when I’m running straight from eclipse in debug.

    Now I’ve got the required permission INTERNET and I even put ACCESS_NETWORK_STATE to check my network status – and when I do check it says I have internet access.
    If I change my package name from com.name.game to com.name.game.android (as in the manifest) the dialog says it’s incorrectly configured so I assume com.name.game is correct.
    I’ve also checked that under Game Services -> Testing I have my account listed as a Tester.
    I’ve gone through and unpackaged the apk and checked the SHA1 and it’s correct to the one eclipse uses debug.keystore.

    It says “The Google Play game services settings are ready to test.” so I assume it should work, right?

    Can you think of anything that might have gone wrong?

    • Ralph states: September 1, 2014 at 8:00 am

      Alright, well, it really could be any number of things, but one thing you said caught my eye:

      “I’ve also checked that under Game Services -> Testing I have my account listed as a Tester.

      What account is that? I remember reading something a while back that you shouldn’t use your main developer account (the one under which the game is uploaded to Google) when testing. It’s better to create (or use another) dummy account.

      • Kyle proclaims: September 1, 2014 at 6:56 pm

        I tried with both dev account and non-dev account – same result.
        This morning when I woke up I linked a second app with package com.name.game.android. so now I have both the *.android and non-.android client ids. Plugged into my tablet running android 4.0.3 which only has my non-dev account and hey look, it works!
        Plugged into my phone running android 4.4.2 has both accounts. “Failed to sign in. Check network…” for both accounts. I removed my dev account and restarted the phone thinking it may be conflicting. Same problem.

        Now I’m curious, can it still be a configuration problem in the dev console? since it works on my tablet fine. But I have no problems with other apps that use the play services on my phone.

        Looking at the logcat output, on tablet beginUserInitiatedSignIn: … connected. on phone I get beginUserInitiatedSignIn: … Connection failure: code: SIGN_IN_REQUIRED. it attempts to resolve it but gets SIGN_IN_FAILED and gives up.

        • Kyle blathers: September 2, 2014 at 2:15 am

          Just an update: I’ve tested it on different devices with different email address and it all works. So there’s nothing wrong with the setup.

          Thanks for you help! Since the problem is with my phone and not related to this article I’ll go seek help on the appropriate forums.

          Thanks again!

  6. Antoine states: September 9, 2014 at 7:27 pm

    Hi Ralph,

    Just like everyone else mentioned, great tut!! I got one question. What about the ios project of the libgdx? How to set it up?

    • Ralph utters: September 9, 2014 at 8:08 pm

      Funny you should mention, I just ordered a used Macbook Pro so I can begin porting my app to ios. This will be my first adventure into ios-land, so I will have to learn how to do exactly what you’re asking – maybe I’ll make a part 2 of this tutorial for it!

      • Antoine proclaims: September 9, 2014 at 10:47 pm

        I don’t know if you have had the chance to see this yet, but this looks interesting -> Robovm Bindings:

        https://github.com/Michingo/com.michingo.robovmbindings/tree/master/Google%20Play%20Game%20Services%20Sample

      • Raymond proclaims: September 19, 2014 at 8:07 am

        Excellent tutorial, I cannot thank you enough! I haven’t gotten the chance to test on an proper device yet, and I can’t seem to be able to sign in on the android emulator. Any ideas on how to prompt the user to sign in?

        Also, how can I keep updated on a possible future tutorial for iOS? I can’t wait!

        Thanks again,
        Raymond

        • Ralph says: September 22, 2014 at 8:26 am

          Hey Raymond.

          Well, I believe the Google Play Services is built in such a way that it immediately prompts the user to sign in as soon as the app starts up.

          I actually didn’t like this functionality so I disabled it with:
          _gameHelper.setMaxAutoSignInAttempts(0);

          I know that doesn’t really answer you’re question, but I’m unsure myself. You should be able to find a way on Google.

          As for the potential iOS tutorial, you can always follow me on twitter (/shameless) which would honestly be the best way to hear of a new post.

          I’ve actually been a bit delayed with getting to work with iOS, got a defective used Macbook Pro from eBay, so it’ll be at least another two weeks until I’d be able to write a tutorial.

        • Raymond utters: September 22, 2014 at 8:53 am

          Thanks for the reply. I don’t have twitter so I’ll just check back here in occasionally 🙂 Looking forward to your tutorial!

  7. Silvio utters: September 25, 2014 at 2:05 pm

    I´m having problems with the setup. When I created the GameHelper field in my android launcher it cannot be resolved to a type. I cannot import it from BaseGameUtils. I set it up exactly like you but it doesn´t seem to work. When I look into the BaseGameUtils project I imported, the 4 classes which include GameHelper are in the java/com/google/example/games/basegameutils/ folder, but the src package in the project is emply. what could I have done wrong?

    • Silvio announces: September 25, 2014 at 5:27 pm

      okay I solved this on my own somehow.
      I changed the source folders on build path from /src to /java.
      then I followed the rest of the tutorial and I am having even bigger problems. I´m using netbeans for the game coding and eclipse for things like googe play services, because I have no clue how to do it in Netbeans. I clicked everything. its not like in eclipse that you just right click on project and so on. I can´t understand this. I love Netbeans for coding but its totally so bad if you do anything with libgdx that includes libraries and so. Thats why I do that in Eclipse. When I once added google play services in Eclipse, Netbeans would recognize it and everything worked fine, but now netbeans says “package com.example.games.basegameutils does not exist. I really dont know how to tell netbeans where it is.
      I sitting here for hours trying everything. Because of that error in netbeans, I cant start the app there. Eclipse is also giving me an error when starting, but it says

      “Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory.
      Could not execute build using Gradle distribution ‘http://services.gradle.org/distributions/gradle-1.11-all.zip’.”

      this is all so frustrating. on top of that, you can´t really find help on the internet, since not many people use netbeans with libgdx, it seems.

      • Ralph proclaims: September 25, 2014 at 5:37 pm

        Trust me, been there done that. It seems like a bunch of nonsense going on.

        I know you’re probably not going to want to hear this, but I recommend just starting fresh – and using Eclipse. I’m certain you can use Netbeans to do all of this stuff, but for every library I’ve seen when it comes to Android stuff – there’s always tutorials for Eclipse specifically. I’m sorry I can’t really help much, there’s too many variable to determine exactly what’s going on.

        I’m not sure what that JDK error message is about – I’d look into re-downloading the latest Java JDK and setting the JAVA_HOME property like it states, then trying to open up Eclipse again.

        But above all I recommend just using Eclipse.

        • Silvio utters: September 25, 2014 at 6:07 pm

          Okay the JDK error is gone now. So when I try to run the android subproject, eclipse now also says

          “error: package com.google.example.games.basegameutils does not exist”

          although in the editor it shows no errors.

          okay fresh start. I removed the BaseGameUtils and did the tutorial again.

          now inside the GameHelper class on line 112 this error occurs:

          “The type android.support.v4.app.FragmentActivity cannot be resolved. It is indirectly referenced from required .class files”

          like someone on stackoverflow said, I right click on the BaseGameUtils project -> Android tools -> Add Support library. after that the errors disappar in the editor, but still occur when I try to start the game on android.

          any idea what I could do now?

          I often thought about moving to eclipse, since its used by almost every one. I only stayed with netbeans because of small tricks like autointend which I haven´t found on eclipse yet. so its okay for me to use eclipse from now. netbeans just seemed a bit more noob friendly in the beginning.

        • Ralph proclaims: September 25, 2014 at 6:22 pm

          First off, I believe auto-indent is shift+ctrl+f in Eclipse, if I understand you correctly. I actually just found that out myself not too long ago.

          Anyway, you really present a tough problem. I really wish I could help more, but like I said, I’m away from my workspace right now.

          I hate to suggest such a dumb solution, but try cleaning your project and see if it helps anything. I’ve been stuck in similar situations in the past and Project>Clean sometimes helped for whatever reason.

    • Ralph announces: September 25, 2014 at 5:58 pm

      I’m not sure if you’re beyond this issue, but MAKE SURE you’re importing the right thing.

      I remember when I was first doing this I was having similar issues, good thing I took this screenshot.

      Make sure when you’re importing, everything looks like that.

      Sorry I can’t be of more help, it’s been a while since I’ve worked with these types of things and I’m away from my workspace.

      • Silvio blathers: September 25, 2014 at 8:34 pm

        okay after hours I think gradle is the thing thats not working. can’t find any solution on the internet. I think I’m giving up.
        This is one of the few times I hate coding and the internet. Its so weird, I’m doing exactly what everyone else does and it doesn’t work.

  8. Avi utters: September 26, 2014 at 5:30 pm

    Hi Ralph,

    First of all I would like to say thank you for the awesome tutorial.

    But i have some problems.

    The “BaseGameUtils” project seems to be updated, and is now different than it was when you made the tutorial.
    The project is strangely called “main” instead of “BaseGameUtils” when you import it, and doesn’t work.
    I have followed all of your steps a few times already and I just don’t understand what I do wrong. GameHelper cannot be resolved to a type for example.

    thanks

    • Silvio says: September 26, 2014 at 5:56 pm

      I’m trying to get this to work since yesterday. Came across the same problem. so apparently they have updated the BaseGameUtils project, so it works better with Android Studio, but Eclipse won’t recognize it properly anymore. This is the old version, which is similar like the on in this tutorial:

      https://docs.google.com/file/d/0BwANZFc0H24cOWlNRFlaOGtLbnc/edit

      weird file format, never seen it before, but 7zip worked for me to unzip.

      I also read the GameHelper class in there is outdated, so this is a new version made by community:

      https://gist.github.com/EmmanuelVinas/ef09a35bcc805ba6deb3

      and I found an official script to transform the new BaseGameUtils project into this, in this tutorial

      https://github.com/hak/android-samples/commit/089566fa36ea900b2bdd9e75882d09e4e23b5ac4

      but I haven’t tried this script, since the first link provides you with the old version.

      After using this, my eclipse atleast throws no errors in the editor anymore. The android subproject still doesn’t run, but thats gradles fault. I’m working on a solution.

      hope this helps. This is 2 days of research and frustration 😀

      • Avi utters: September 27, 2014 at 3:56 am

        Thank you very much Silvio!
        But I don’t understand how do i run the script.

        • Silvio remarks: September 27, 2014 at 3:05 pm

          yeah I don’t know either. I copied it into a .bat file but get errors.

          Is anything working for you?

          when I try to build the android project it says:
          error: package com.google.example.games.basegameutils does not exist

        • Ralph says: September 27, 2014 at 5:06 pm

          Yeah, it seems a lot of these problems seem to be stemming from the fact that the library files mentioned in the post have since been updated.

          It might be time for an update once I get my schedule cleared up.

    • Avi says: September 26, 2014 at 6:01 pm

      I solved it somehow.
      I moved the package with the 4 classes to the src folder, and then added the jar (v4 something) that came with the samples to the build path of “main”. It seems to be working now.

    • Sarang proclaims: October 23, 2014 at 9:04 am

      Hey Avi,
      I was having the same problem, heres the solution –

      in the android-basic-sampes folder there is a Scripts folder. open it you will find a make_eclipse_compat script. (.cmd for windows). Go to the android-basic-samples directory and run the script from a terminal.

      now you will have an eclipse_compat folder besides the Script folder. Import the BaseGameUtils project from the eclipse_compat folder and do further steps (referencing and all).

      The official documentation is incomplete. the BaseGameUtils project as it is , is not compatible for eclipse..

      Hope this helps..

  9. Juwal Bose announces: October 12, 2014 at 3:08 pm

    The BaseGameUtils have been updated to support Android Studio by default. We need to create eclipse compatible project structure by running the Scritps/make_eclipse_compat script after copying it to root folder. This will create the needed eclipse compatible projects. Use it instead.

  10. Brent Autry says: November 5, 2014 at 7:24 pm

    So after much frustration I finally got this figured out for me as well.

    First off make sure you have the most recent version of google-play-services_lib. Go into your android sdk manager and update it and reimport the project if you are unsure. I had issues with some imports not getting resolved in the GameHelper class inside of BaseGameUtils project.

    Then go into the Scripts folder, copy everything inside of that directory up one folder (same folder that BasicSamples exists in).

    Run make_eclipse_compat.cmd

    Import the project eclipse_compat\libraries\BaseGameUtils

  11. Puda says: November 9, 2014 at 11:34 pm

    Thank you so much!! You helped me a lot!!

  12. Dave proclaims: November 19, 2014 at 7:56 am

    Everything seems to fall into place until I get to

    1
    initialize(new Game(this),cfg

    I get “MyGame() in MyGame cannot be applied to com.labrat.mygame.android.MainActivity”

    1
    initialize(new MyGame(),cfg

    works

    • Dave proclaims: November 19, 2014 at 7:59 am

      (Missing closing parenthesis on both code examples is a typo, they are there in theactual source)

  13. Guillermo remarks: December 21, 2014 at 1:27 am

    Thank you. You are a master!

    I need help.. How i use the different functions of API from my core project? e.g When i press a button, i want sign out of Google. Or send a score to ranking.

    Again, thank you very much!

  14. Pratyush Sharma remarks: January 8, 2015 at 3:00 am

    Hey I am having a problem, I have followed all the steps and everything is building fine though I don’t get the prompt to sign in.
    How do I debug?

  15. Matthew announces: January 8, 2015 at 6:07 pm

    For those of you who were not able to run the eclipse_compat script on osx (or windows I suppose), I was able to create the compatible BaseGameUtils project manually.

    1. create a new folder (anywhere) called eclipse_compat

    2. create a folder inside that called BaseGameUtils

    3. navigate to BasicSamples/libraries/BaseGameUtils/src/main

    4. Copy AndroidManifest.xml into the new BaseGameUtils folder

    5. copy BasicSamples/libraries/BaseGameUtils/src/main/res into your new BaseGameUtils folder

    (Your folder should now look like:

    /AndroidManifest.xml
    /res/…
    )

    6. Navigate to BasicSamples/libraries/BaseGameUtils/src/main/java

    7. copy BasicSamples/libraries/BaseGameUtils/src/main/java/com

    8. In your new BaseGameUtils create a folder called src

    9. paste the com folder you have just copied into the new src folder

    10. Navigate to Scripts/eclipse_aux and copy the android-support-vX.jar

    11. In your new BaseGameUtils folder create a folder called libs

    12. Paste the jar you just copied into the libs folder

    Your folder structure should look like this

    eclipse_compat/BaseGameUtils/AndroidManifest.xml
    eclipse_compat/BaseGameUtils/src/com/…
    eclipse_compat/BaseGameUtils/res/…
    eclipse_compat/BaseGameUtils/libs/…

    import this project into eclipse as an existing android code project and everything should work fine

  16. Adam Napier remarks: January 18, 2015 at 11:34 pm

    How would I go about showing my achievements? I already have them made in the dev console and have them stored in my ids.xml file I just need to figure out how to programmatically insert my achievements.

  17. Adam Napier says: January 18, 2015 at 11:35 pm

    BTW I found this walkthrough and all comments to be extremely helpful everyone I appreciate all of the help from all of you.

  18. Matthew remarks: January 18, 2015 at 11:40 pm
  19. Matthew remarks: January 18, 2015 at 11:41 pm

    In response to Adam

  20. Demirhan Karademir utters: January 19, 2015 at 9:08 am

    Thanks so much!

  21. Ralph says: January 19, 2015 at 12:45 pm

    Hey everyone, I just want to thank everyone in the comments here providing new/updated information and fixes.

    Also thanks to you helping others out. I haven’t worked with this area of Android development in a while so I’m a bit in the dark with this stuff at the moment.

  22. Josh says: January 20, 2015 at 8:46 pm

    Yup, that did it. Thanks! Fwiw, I couldn’t use the resulting Eclipse project (BaseGameUtils) as a library, so I just put the project on the build path for my main game project.

  23. Robert utters: January 22, 2015 at 1:27 pm

    Hi, thanks for the tutorial. I’m having a problem with exporting the .APK from Eclipse, I get an error stating that the “GC overhead limit was exceeded”. I allocated more memory to Eclipse in the .ini file but it hasn’t helped. Is anyone else experiencing this issue?

  24. Adam Napier utters: January 26, 2015 at 11:00 pm

    Thanks Matthew for the reply. After reading through your suggested tutorial I found some code to be missing. In the androidlauncher.java file. In that file you will need this method to get your achievements working

    public void unlockAchievement(String achievementId) {
    Games.Achievements.unlock(_gameHelper.getApiClient(), achievementId );
    }

  25. Stefan utters: January 27, 2015 at 6:58 pm

    Thank you

  26. Adam Napier says: January 28, 2015 at 2:13 am

    I know this may not be the best place to ask this question because it is a bit off topic. One of my achievements requires me to know which day of the weeks it is. I have looked at the javadocs for TimeUtils, but do not know if I an get what I need by their provided methods.

  27. Adam Napier blathers: January 28, 2015 at 2:15 am

    Also here is the code to show your achievements
    startActivityForResult(Games.Achievements.getAchievementsIntent(_gameHelper.getApiClient()), 1000);

  28. Ralph remarks: January 28, 2015 at 8:12 am

    Hey Adam, you can maybe get away with using Calendar. Found this on StackOverflow:

    1
    2
    3
    Calendar c = Calendar.getInstance();
    c.set(year, month, day);
    int day_of_week = c.get(Calendar.DAY_OF_WEEK);
  29. Adam Napier remarks: January 28, 2015 at 2:05 pm

    Thanks Ralph, but I am looking for a way to do it in LibGdx so it will be compatible across all devices. Anyone know if it is possible?

  30. Adam Napier says: January 28, 2015 at 9:06 pm

    Wouldn’t it only work for the Android version seeing as it is java also if I did use this do you know how I can tell what day it is from an integer? I appreciate your help Ralph.

  31. Ralph blathers: January 29, 2015 at 8:07 am

    Well, if you’re referring to this being compatible with the iOS version then, isn’t everything Java? RoboVM takes care of converting it to work on iOS devices.

    As for the returned integer, from looking at the docs (http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.util.Calendar.DAY_OF_WEEK) you can see that Sunday is 1 and Saturday is 7, with everything else in between.

    Hope that helps.

  32. Adam utters: January 29, 2015 at 4:03 pm

    Thank you Ralph it is much appreciated. When I have time I will implement this and post you on if I can fire off this achievement properly.

  33. Jeudy utters: January 30, 2015 at 10:58 pm

    This tutorial was really GREAT. Thanks!

  34. David states: February 21, 2015 at 5:40 pm

    Hey sir,

    I followed all your steps. When I try to debug, I keep getting this error in logcat and the application crashes.

    02-21 16:31:13.714 10123-10123/com.fullsail.djones.android.ninjaquest.android E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.fullsail.djones.android.ninjaquest.android, PID: 10123
    java.lang.NoClassDefFoundError: com.google.example.games.basegameutils.R$string
    at com.google.example.games.basegameutils.GameHelperUtils.(GameHelperUtils.java:32)
    at com.google.example.games.basegameutils.GameHelper.onConnectionFailed(GameHelper.java:798)
    at com.google.android.gms.internal.jm.b(Unknown Source)
    at com.google.android.gms.common.api.c.gJ(Unknown Source)
    at com.google.android.gms.common.api.c.d(Unknown Source)
    at com.google.android.gms.common.api.c$4.onConnectionFailed(Unknown Source)
    at com.google.android.gms.internal.jm.b(Unknown Source)
    at com.google.android.gms.internal.jl$h.b(Unknown Source)
    at com.google.android.gms.internal.jl$h.g(Unknown Source)
    at com.google.android.gms.internal.jl$b.hy(Unknown Source)
    at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5001)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    at dalvik.system.NativeStart.main(Native Method)

    Any ideas?

    Thanks!

  35. Matthew utters: February 21, 2015 at 6:04 pm

    David, have you checked the “is library” box in the project properties of the BaseGameUtils. (Properties -> Android -> Is Library) Also, make sure that Android Private Libraries is checked in Order and Export. if it isn’t checked,check it and restart eclipse.

  36. David utters: February 21, 2015 at 6:22 pm

    I’m using Android Studio actually. That’s what they told us to use for our class projects.

  37. David proclaims: February 21, 2015 at 6:40 pm

    I’m an idiot.

    My device needed updated. Problem resolved.

  38. Fredrik states: February 27, 2015 at 12:56 pm

    Did you ever solve this? Having the same issue 🙁

  39. Adam states: February 27, 2015 at 11:10 pm

    Hi guys sorry I have been busy just wanted to update you all. I was able to fire off the achievement correctly in my app using Ralph’s advice….thanks again. I now am facing another difficult challenge. I currently use the following class level variables.

    position = new Vector2(x, y);
    velocity = new Vector2(0, 0);

    I then update like so:
    velocity.add(acceleration.cpy().scl(delta));
    position.add(velocity.cpy().scl(delta));

    My issue is that because the previous two lines are being called in my update method it instantiates a ridiculous amount of objects. Are there better ways to go about this, without all of the unnecessary objects. I ask this because occasionally my app will experience a drop in fps and I believe this is the issue.

  40. Adam proclaims: April 3, 2015 at 1:32 am

    I ended up just using class variables as opposed to using vectors for some reason that method creates many objects. Well I have finally released my app on google play (It is my first) please check it out the name is “Tap n Flap” and let me know what you think. I also could not have done it without the people here so thank you all for your help.

  41. Eagle proclaims: May 26, 2015 at 11:36 am

    A great tutorial, but until the point you state that we need the APP ID I just can’t find it! I looked everywhere but its not in the developer console. Do you have any idea where it might be in the newest version?

    Thanks!

  42. RTDEV blathers: May 26, 2015 at 5:30 pm

    LOVE YOU THANKS!!

  43. rufodev announces: August 11, 2015 at 8:15 am

    There is no MainActivity.java in a LibGDX project….is there?

  44. rufodev says: August 11, 2015 at 9:51 am

    this is what i have on my libgdx project setup under eclipse ide:
    File: AndroidLauncher.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.somename.gamename.android;

    import android.os.Bundle;

    import com.badlogic.gdx.backends.android.AndroidApplication;
    import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
    import com.somename.gamename.MyGame;

    public class AndroidLauncher extends AndroidApplication {
       
        @Override
        protected void onCreate (Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
            initialize(new MyGame(), config);
        }
       
    }

    If the case is that i should include the GameHelper here, i cant figure out how. Also I’m biased not to try since you said there should be a MainActivity.java file…

  45. rufodev remarks: August 11, 2015 at 1:49 pm

    Sorry, im a tool. MainActivity.java is replaced for AndroidLauncher.java on newest versions of libgdx library.
    So in my case everything you mention about MainActivity.java i should do into AndroidLauncher.java.
    Epic tutorial btw man! thanks a bounch!

  46. Pavel utters: August 30, 2015 at 7:01 pm

    I have the same problem.

    Steps to reproduce:

    – Create an empty libgdx project with Box2d only.
    – import the most recent google play services (ver 23)
    – link android project against google play services
    – run application

    conversion to dalvik format failed with error 1

  47. Pavel says: August 30, 2015 at 7:21 pm

    I was able to solve this by unchecking the following in the Eclipse: Project–> properties–>Java Build Path

    Android Private Libraries
    Android Dependencies
    Android X.Y.Z

Post a Comment

You must be logged in to post a comment.