Start classes & configuration

View: 662    Dowload: 0   Comment: 0   Post by: daii   Category: Mobile applications   Fields: Game - Entertainment

For each target platform, a starter class has to be written. This class instantiates a back-end specificApplication implementation and the ApplicationListener that implements the application logic. The starter classes are platform dependent, let's have a look at how to instantiate and configure these for each back-end.

This article assumes you have followed the instruction in Project Setup, Running & Debugging and have imported the generated core, desktop, Android and HTML5 projects into Eclipse.

Desktop (LWJGL)

Opening the class in my-gdx-game shows the following:


import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
   public static void main(String[] args) {
      LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
      cfg.title = "my-gdx-game";
      cfg.useGL30 = false;
      cfg.width = 480;
      cfg.height = 320;

      new LwjglApplication(new MyGdxGame(), cfg);

First an LwjglApplicationConfiguration is instantiated. This class lets one specify various configuration settings, such as the initial screen resolution, whether to use OpenGL ES 2.0 or 3.0 (Experimental) and so on. Refer to the Javadocs of this class for more information.

Once the configuration object is set, an LwjglApplication is instantiated. The MyGdxGame() class is the ApplicationListener implementing the game logic.

From there on a window is created and the ApplicationListener is invoked as described in The Life-Cycle

Desktop (LWJGL3)

To come...


Android applications do not use a main() method as the entry-point, but instead require an Activity. Open the class in the my-gdx-game-android project:


import android.os.Bundle;


public class MainActivity extends AndroidApplication {
    public void onCreate(Bundle savedInstanceState) {

        AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();

        initialize(new MyGdxGame(), cfg);

The main entry-point method is the Activity's onCreate() method. Note that MainActivity derives from AndroidApplication, which itself derives from Activity. As in the desktop starter class, a configuration instance is created (AndroidApplicationConfiguration). Once configured, theAndroidApplication.initialize() method is called, passing in the ApplicationListener,MyGdxGame)\ as well as the configuration. Refer to the AndroidApplicationConfiguration Javadocsfor more information on what configuration settings are available.

Android applications can have multiple activities. Libgdx games should usually only consist of a single activity. Different screens of the game are implemented within libgdx, not as separate activities. The reason for this is that creating a new Activity also implies creating a new OpenGL context, which is time consuming and also means that all graphical resources have to be reloaded.

Fragment based libgdx

The Android SDK has introduced an API to create controllers for specific parts of a screen, that can be easily re-used on multiple screens. This API is called the Fragments API. Libgdx can now also be used as a part of a larger screen, inside a Fragment. To create a Libgdx fragment, subclassAndroidFragmentApplication and implement the onCreateView() with the following initialization:

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return initializeForView(new MyGdxGame());

That code depends on some other changes to the -android project:

  • 1. Add Android V4 Support Library to the -android project and its build path if you haven't already added it. This is needed in order to Extend FragmentActivity later
  • 2. Change AndroidLauncher activity to extend FragmentActivity, not AndroidApplication
  • 3. Implement AndroidFragmentApplication.Callbacks on the AndroidLauncher activity
  • 4. Create a Class that extends AndroidFragmentApplication which is the Fragment implementation for Libgdx.
  • 5. Add the initializeForView() code in the Fragment's onCreateView method.
  • 6. Finally, replace the AndroidLauncher activity content with the Libgdx Fragment.

For example:

// 2. Change AndroidLauncher activity to extend FragmentActivity, not AndroidApplication
// 3. Implement AndroidFragmentApplication.Callbacks on the AndroidLauncher activity
public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks
   protected void onCreate (Bundle savedInstanceState)

      // 6. Finally, replace the AndroidLauncher activity content with the Libgdx Fragment.
      GameFragment fragment = new GameFragment();
      FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
      trans.replace(, fragment);

   // 4. Create a Class that extends AndroidFragmentApplication which is the Fragment implementation for Libgdx.
   private class GameFragment extends AndroidFragmentApplication
      // 5. Add the initializeForView() code in the Fragment's onCreateView method.
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
      {  return initializeForView(new MyGdxGame());   }

   public void exit() {}

The AndroidManifest.xml File

Besides the AndroidApplicationConfiguration, an Android application is also configured via theAndroidManifest.xml file, found in the root directory of the Android project. This might look something like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />

        android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


Target Sdk Version

Set this to the version of Android you want to target.

Screen Orientation & Configuration Changes

In addition to the targetSdkVersion, the screenOrientation and configChanges attributes of the activity element should always be set.

The screenOrientation attribute specifies a fixed orientation for the application. One may omit this if the application can work with both landscape and portrait mode.

The configChanges attribute is crucial and should always have the values shown above. Omitting this attribute means that the application will be restarted every time a physical keyboard is slid out/in or if the orientation of the device changes. If the screenOrientation attribute is omitted, a libgdx application will receive calls to ApplicationListener.resize() to indicate the orientation change. API clients can then re-layout the application accordingly.


If an application needs to be able to write to the external storage of a device (e.g. SD-card), needs internet access, uses the vibrator or wants to record audio, the following permissions need to be added to the AndroidManifest.xml file:

    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

Users are generally suspicious of applications with many permissions, so chose these wisely.

For wake locking to work, AndroidApplicationConfiguration.useWakeLock needs to be set to true.

If a game doesn't need accelerometer or compass access it is advised to disable these by setting the useAccelerometer and useCompass fields of AndroidApplicationConfiguration to false.

If your game needs the gyroscope sensor, you have to set useGyroscope to true inAndroidApplicationConfiguration (It's disabled by default, to save energy).

Please refer to the Android Developer's Guide for more information on how to set other attributes like icons for your application.

Live Wallpapers

Libgdx features a simple to use way to create Live Wallpapers for Android. The starter class for a live wallpaper is called AndroidLiveWallpaperService, here's an example:

package com.mypackage;

// imports snipped for brevity 

public class LiveWallpaper extends AndroidLiveWallpaperService {
    public ApplicationListener createListener () {
        return new MyApplicationListener();

    public AndroidApplicationConfiguration createConfig () {
        return new AndroidApplicationConfiguration();

    public void offsetChange (ApplicationListener listener, float xOffset, float yOffset, float xOffsetStep, float yOffsetStep,
        int xPixelOffset, int yPixelOffset) {"LiveWallpaper", "offset changed: " + xOffset + ", " + yOffset);

The methods createListener() and createConfig() will be called when your live wallpaper is shown in the picker or when it is created to be displayed on the home screen.

The offsetChange() method is scaled when the user swipes through screens on the home screen and tells you by how much the screen is offset from the center screen. This method will be called on the rendering thread, so you don't have to synchronize anything.

In addition to a starter class, you also have to create an XML file describing your wallpaper. Let's call that livewallpaper.xml. Create a folder called xml/ in your Android project's res/ folder and put the file in there (res/xml/livewallpaper.xml). Here's what to put into that file:

<?xml version="1.0" encoding="UTF-8"?>

This defines the thumbnail to be displayed for your LWP in the picker, the description and an Activity that will be displayed when the user hits "Settings" in the LWP picker. This should be just a standard Activity that has a few widgets to change settings such as the background color and similar things. You can store those settings in SharedPreferences and load them later in your LWPs ApplicationListener via

Finally, you'll need to add things to your AndroidManifest.xml files. Here's an example for an LWP with a simple settings Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14"/> 
    <uses-feature android:name="" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LivewallpaperSettings" 
                  android:label="Livewallpaper Settings"/>

        <service android:name=".LiveWallpaper"
                <action android:name="android.service.wallpaper.WallpaperService" />
            <meta-data android:name="android.service.wallpaper"
                android:resource="@xml/livewallpaper" />

The manifest defines:

  • it uses the live wallpaper feature, see <uses-feature>.
  • a permission to be allowed to bind the wallpaper, see android:permission
  • the settings activity
  • the livewallpaper service, pointing at the livewallpaper.xml file, see meta-data

Note that live wallpapers are only supported starting from Android 2.1 (SDK level 7).

LWPs have some limitations concerning touch input. In general only tap/drop will be reported. If you want full touch you can see theAndroidApplicationConfiguration#getTouchEventsForLiveWallpaper flag to true to receive full multi-touch events.


Since Android 4.2, users can set Daydreams that will get displayed if the device is idle or docked. These daydreams are similar to screensavers and can display things like photo albums etc. Libgdx let's you write such daydreams easily.

The starter class for a Daydream is called AndroidDaydream. Here's an example:


import android.annotation.TargetApi;
import android.util.Log;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.tests.MeshShaderTest;

public class Daydream extends AndroidDaydream {
   public void onAttachedToWindow() {

      AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
      ApplicationListener app = new MeshShaderTest();
      initialize(app, cfg);

Simply derive from AndroidDaydream, override onAttachedToWindow, setup your configuration and ApplicationListener and initialize your daydream.

In addition to the daydream itself you can provide a settings activity that lets the user configure your daydream. This can be a normal activity, or a libgdx AndroidApplication. An empty activity as an example:



public class DaydreamSettings extends Activity {


This settings activity must be specified as metadata to the Daydream service. Create an xml file in the res/xml folder of your Android project and specify the activity like this:

<dream xmlns:android=""
 android:settingsActivity="" />

Finally, add a section for the settings activity in the AndroidManifest.xml as usual, and a service description for the daydream, like this:

<service android:name=".Daydream"
       <action android:name="android.service.dreams.DreamService" />
       <category android:name="android.intent.category.DEFAULT" />
   <meta-data android:name="android.service.dream"
       android:resource="@xml/daydream" />


To come..


The main entry-point for an HTML5/GWT application is a GwtApplication. Open GwtLauncher.javain the my-gdx-game-html5 project:


import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;

public class GwtLauncher extends GwtApplication {
   public GwtApplicationConfiguration getConfig () {
      GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(480, 320);
      return cfg;

   public ApplicationListener createApplicationListener () {
      return new MyGdxGame();

The main entry-point is composed of two methods, GwtApplication.getConfig() andGwtApplication.createApplicationListener(). The former has to return aGwtApplicationConfiguration instance, which specifies various configuration settings for the HTML5 application. The GwtApplication.createApplicatonListener() method returns theApplicationListener to run.

Module Files

GWT needs the actual Java code for each jar/project that is referenced. Additionally, each of these jars/projects needs to have one module definition file, having the suffix gwt.xml.

In the example project setup, the module file of the html5 project looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "">
   <inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' />
   <inherits name='MyGdxGame' />
   <entry-point class='' />
   <set-configuration-property name="gdx.assetpath" value="../my-gdx-game-android/assets" />

This specifies two other modules to inherit from (gdx-backends-gwt and the core project) as well as the entry-point class (GwtLauncher above) and a path relative to the html5 project's root directory, pointing to the assets directory.

Both the gdx-backend-gwt jar and the core project have a similar module file, specifying other dependencies. You can not use jars/projects which do not contain a module file and source!

For more information on modules and dependencies refer to the GWT Developer Guide.

Reflection Support

GWT does not support Java reflection for various reasons. Libgdx has an internal emulation layer that will generate reflection information for a select few internal classes. This means that if you use the Json serialization capabilities of libgdx, you'll run into issues. You can fix this by specifying for which packages and classes reflection information should be generated for. To do so, you can put configuration properties in your GWT project's gwt.xml file like so:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    ... other elements ...
    <extend-configuration-property name="gdx.reflect.include" value="org.softmotion.explorers.model" />
    <extend-configuration-property name="gdx.reflect.exclude" value="org.softmotion.explorers.model.HexMap" />

You can add multiple packages and classes by adding more extend-configuration-property elements.

This feature is experimental, use at your own risk.

Loading Screen

A libgdx HTML5 application preloads all assets found in the gdx.assetpath. During this loading process, a loading screen is displayed which is implemented via GWT widget. If you want to customize this loading screen, you can simply overwrite theGwtApplication.getPreloaderCallback() method (GwtLauncher in the above example). The following example draws a very simple, ugly loading screen using Canvas:

long loadStart = TimeUtils.nanoTime();
public PreloaderCallback getPreloaderCallback () {
  final Canvas canvas = Canvas.createIfSupported();
  canvas.setWidth("" + (int)(config.width * 0.7f) + "px");
  final Context2d context = canvas.getContext2d();
  context.setFont("18pt Calibri");

  return new PreloaderCallback() {
     public void done () {
        context.fillRect(0, 0, 300, 40);

     public void loaded (String file, int loaded, int total) {
        System.out.println("loaded " + file + "," + loaded + "/" + total);
        String color = Pixmap.make(30, 30, 30, 1);
        context.fillRect(0, 0, 300, 70);
        color = Pixmap.make(200, 200, 200, (((TimeUtils.nanoTime() - loadStart) % 1000000000) / 1000000000f));
        context.fillRect(0, 0, 300 * (loaded / (float)total) * 0.97f, 70);

        context.setFillStyle(Pixmap.make(50, 50, 50, 1));
        context.fillText("loading", 300 / 2, 70 / 2);

     public void error (String file) {
        System.out.println("error: " + file);

Note that you can only use pure GWT facilities to display the loading screen, libgdx APIs will only be available after the preloading is complete.

Start classes & configuration

For each target platform, a starter class has to be written. This class instantiates a back-end specificApplication implementation and the ApplicationListener that implements the application logic. The starter classes are platform dependent, let's have a look at how to instantiate and configure these for each back-end.

Posted on 18-11-2016 


To comment you must be logged in members.

Files with category

  • 8-bit LED Binary Counter

    8-bit LED Binary Counter

    View: 22    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Other

    This article offers a simple implementation of the binary counter powered by Raspberry PI3 and 8 LEDs. It is very similar to what was done before for Arduino board in the previous article Connecting an Arduino to a Breadboard to Light Up LEDs. In...

  • Chat App

    Chat App

    View: 29    Download: 1   Comment: 0

    Category: Android     Fields: none

    This is a Chat App for Android mobile. You can make separate chat with you partner. I'm using Mysql Database and Php code and All APIs are develop on PHP (REST APIs). My whatsApp:+918285672453: Email ID:

  • Tower Defense 3D

    Tower Defense 3D

    View: 24    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    The goal in this game is to protect your territory against the attacking enemies. Place defensive structures on or along their path of attack to prevent them reaching your base. Strategic choice and positioning of defensive elements is an essential...

  • Flap the Bird

    Flap the Bird

    View: 21    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tap your screen to make the bird fly. While you are flying there are destruction that will stop you. Avoid hitting the floor and flying to high this will deduct your life. You can collect coins and life along the way. For more mobile games and...

  • Bad Santa

    Bad Santa

    View: 26    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This is a simple shooting game where the Bad Santa is shooting the bad snowman and reindeer. You can collect coins and life along the way. For more mobile games and tutorials you can visit this site.

  • Flappy Halloween Game

    Flappy Halloween Game

    View: 23    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Flappy Halloween is a simple game, tap the screen to move the player. Shoot the pumpkin in the ring to gain score. Avoid hitting the flying destructions and falling from the ground. Since the Halloween is coming this game is really perfect to play...

  • Tilt Ball Game

    Tilt Ball Game

    View: 23    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This game is simple you need to tilt your device to make the ball move in your own desired direction. Reach the finish line before the time ends and move to the next level.

  • Sky Rise 3D Game

    Sky Rise 3D Game

    View: 42    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Game - Entertainment

    Stack up the blocks as high as you can to build a tower. Align the blocks on top of each other. If you manage to place the block exactly on the one before it, it will not lose size. Sloppy placement on the other hand will cut off the blocks and...

File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd