Click here to Skip to main content
15,884,237 members
Articles / Mobile Apps / Android

How To: Initialize a Game on Android with XPG

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
26 Jan 2012CPOL4 min read 23.2K   9  
How to initialize a game on Android with XPG

This is a continuation of the How To series. This first post is here.

This article will cover:

  • Adding the XPG Live API for Android to your project’s build path in Eclipse
  • Adding the XPG Live API for Android reference in Visual Studio
  • Initializing the XPG Live API in code
  • Handling the initialization response

Prerequisites

Adding the XPG Live API for Android to your Project’s Build Path in Eclipse

Copy the XPG.Android_[VERSION].jar and XPG.Android.Doc_[VERSION].jar to your project’s "assets" folder.

In Eclipse, select your project and refresh it.

Expand the "assets" folder in your project.

Open the context menu on "XPG.Android_[VERSION].jar".

Point to "Build Path" and click "Add to Build Path".

image

You will see XPG.Android_[VERSION].jar under the "Referenced Libraries" node in your project.

image

Open the context menu for the XPG.Android_[VERSION].jar from the "Referenced Libraries" node.

Point to "Build Path" and click "Configure Build Path…"

image

On the "Libraries" tab, under "XPG.Android_[VERSION].jar, select "Javadoc Location" and click "Edit".

image

Select "Javadoc in Archive" and "Workspace File", then click "Browse…".

image

Expand your project and the "assets" folder, then select "XPG.Android.Doc_[VERSION].jar and click "OK".

image

Click "OK" again.

image

Now your project is setup to use XPG Live.

Adding the XPG Live API for Android reference in Visual Studio

For simplicity sake, and because the source code is freely available, we’ll use the XPG Demo Source for MonoDroid. We’ve also installed the stable release of the XPG Live API for MonoDroid. This reference dialog may look a bit different than yours because of other installed Visual Studio extensions.

Right click the "References" node in your solution and select the "Add Reference…" option.

image

Click the "Browse…" button and navigate to "C:\Program Files (x86)\XPG\APIs" on 64-bit or "C:\Program Files\XPG\APIs" on 32-bit.

Select "XPG.Android.dll" and click "Open".

image

Click "Add" then click "Close".

image

Now your project is setup to use XPG Live.

Initializing the XPG Live API in Code

Game initialization is very simple, but does require that you’re registered a free developer account on XPG Live, create a game and activate your first access key. Since we’re using the demo app, we’ve already completed those steps. The first post of this series gives a walk through of the management app and covers games and access keys.

Java Code

Java
XPGAPI.Instance.initialize("DEMOKEY000000001", AndroidGameActivity.this, new InitializeCompleted());

C# Code

C#
XPGAPI.Instance.Initialize("DEMOKEY000000001", this, InitializeCompleted);

This will initialize your game locally unless you haven’t enabled Android as a platform, you fat fingered the access key, or you forgot to activate the access key for your game. In one of these cases, you’ll get back a localized failure response.

Handling the Initialization Response

The XPG Live API for Android is pretty flexible when it comes to event handling. You can handle events on a per call basis with anonymous delegates, delegate method references, or you can wire up event handler to the API instance. The API will only invoke one callback per request. If a delegate was provided in the call, then it will be invoked, if the delegate passed was null then the API instance event will be raised if there is one.

Additionally, the API will raise events on the UI thread by default. This is done to protect against accidental cross thread access of UI components. The XPG Live API for Android DOES NOT directly interact with UI components with the exception of social logins which will be discussed in a later post. You can choose to have your delegate raised on a background thread to keep your main thread free for drawing and updates with the following code:

Java Code

Java
XPGAPI.Instance.setCallbackOnUiThread(false);

C# Code

C#
XPGAPI.Instance.UseUIThreadEvents = false;

If you choose to handle callbacks on background threads, it is your responsibility to manage your cross thread interactions appropriately.

Since this is the first callback you’ll always get, this is a great opportunity to mention that when the initialization call is made is when the server becomes aware of the clients locale. This response, and every response after it, will be sent in the clients locale if at all possible, which means that error messages are not only user friendly but in the users language as well. If you defined game titles and descriptions, etc. for your game in the users language, they will also be used here.

Here’s a simple callback example for game initialization:

Java Code

Java
/** 
* Handle the API having been initialized.
*/
private class InitializeCompleted extends
        XPGAPICallbackGeneric<XPGInitGameInfo> {
    @Override
    public void gotResponse(XPGAPIResponseGeneric<XPGInitGameInfo> response) {
        if (!response.getFailed()) {
            if (response.getBody() == null) {
                Toast.makeText(AndroidGameActivity.this, response.getMessage(), Toast.LENGTH_LONG);
            }
            else {
                /* Use response.getBody() or XPGAPI.Instance to access the game and user */
            }
        }
        else {
            Toast.makeText(AndroidGameActivity.this, response.getMessage(), Toast.LENGTH_LONG);
        }
    }
}

C# Code

C#
///<summary>Handle the API having been initialized.</summary>
///<param name="response">The server response to the initialization.</param>
public void InitializeCompleted(XPGAPIResponse<XPGInitGameInfo> response)
{
    if (!response.Failed)
    {
        if (response.Body == null)
        {
            Toast.MakeText(this, response.Message, ToastLength.Long).Show();
        }
        else
        {
            // Use response.Body or XPGAPI.Instance to access the game and user
        }
    }
    else
    {
        Toast.MakeText(this, response.Message, ToastLength.Long).Show();
    }
}

You’ll notice that not much is going on here. The XPG Live API for Android handles its state so that your game only needs to be concerned with its own state.

During this initialization, the background queue will also spin up to process any score postings, achievement awards, or friend requests which might not have made it to the server before the last shut down.

Announcements for your game are also brought down with initialization, so this callback could be useful for toasts or other user notifications. When this callback is raised, the leaderboards will be initializing their first page of the latest scores already, so there isn’t much for you to do other than handle your game logic.

The Complete Code

Java Code
Java
package com.android.game;

import com.xpglive.api.XPGAPI;
import com.xpglive.api.XPGAPICallbackGeneric;
import com.xpglive.api.XPGAPIResponseGeneric;
import com.xpglive.api.XPGInitGameInfo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class AndroidGameActivity extends Activity {
    /** 
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        XPGAPI.Instance.initialize
        ("DEMOKEY000000001", AndroidGameActivity.this, new InitializeCompleted());
    }

    /** 
     * Handle the API having been initialized.
     */
    private class InitializeCompleted extends
            XPGAPICallbackGeneric<XPGInitGameInfo> {
        @Override
        public void gotResponse(XPGAPIResponseGeneric<XPGInitGameInfo> response) {
            if (!response.getFailed()) {
                if (response.getBody() == null) {
                    Toast.makeText
                    (AndroidGameActivity.this, response.getMessage(), Toast.LENGTH_LONG);
                }
                else {
                    /* Use body or XPGAPI.Instance to access the game and user */
                }
            }
            else {
                Toast.makeText
                (AndroidGameActivity.this, response.getMessage(), Toast.LENGTH_LONG);
            }
        }
    }
}
C# Code
C#
using System;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Widget;
using XPG.Demo.MonoDroid;

namespace XPG.Demo.Android
{
    [Activity(Label = "XPG Demo MonoDroid", 
    MainLauncher = true, Icon = "@drawable/Main")]
    public class ActivityMain : Activity
    {
        ///<summary>Called when the activity is first created.</summary>
        ///<param name="bundle">The saved instance state.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.main);
            XPGAPI.Instance.Initialize("DEMOKEY000000001", this, InitializeCompleted);
        }

        ///<summary>Handle the API having been initialized.</summary>
        ///<param name="response">
        ///The server response to the initialization.</param>
        public void InitializeCompleted(XPGAPIResponse<XPGInitGameInfo> response)
        {
            if (!response.Failed)
            {
                if (response.Body == null)
                {
                    Toast.MakeText(this, response.Message, ToastLength.Long).Show();
                }
                else
                {
                    // Use response.Body or XPGAPI.Instance to access the game and user
                }
            }
            else
            {
                Toast.MakeText(this, response.Message, ToastLength.Long).Show();
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.
This is a Organisation (No members)


Comments and Discussions

 
-- There are no messages in this forum --