For each target platform, a starter class has to be written. This class instantiates a back-end specific Application 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, Importing & Running a Project and therefore have imported the generated core, desktop, Android and HTML5 projects into Eclipse.

Desktop (LWJGL3)

Opening the DesktopLauncher.java class in my-gdx-game shows the following:

  1. package com.me.mygdxgame;
  2. import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
  3. import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
  4. public class DesktopLauncher {
  5. public static void main(String[] args) {
  6. Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
  7. config.setTitle("my-gdx-game");
  8. config.setWindowedMode(480, 320);
  9. new Lwjgl3Application(new MyGdxGame(), config);
  10. }
  11. }

First an Lwjgl3ApplicationConfiguration 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 and so on. Refer to the Javadocs of this class for more information.

Once the configuration object is set, an Lwjgl3Application 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

Common issues:

  1. On macOS, the LWJGL 3 backend is only working when the JVM is run with the -XstartOnFirstThread argument. This can typically be done in the Launch/Run Configurations of your IDE, as is described here. Alternatively, if you’re starting your project via Gradle, add this line to run task of the desktop gradle file:

    1. jvmArgs = ['-XstartOnFirstThread']

    A third approach is to just programatically restart the JVM if the argument is not present (see here for a simple example). Lastly, if you want to deploy your game by packaging a JRE with it (which is the recommended way to distribute your later game), jpackage or packr allow you to set the JVM arguments.

  2. If you are using gdx-tools and the lwjgl3 backend in the same project, you need to modify your gdx-tools dependency like this:

    1. compile ("com.badlogicgames.gdx:gdx-tools:$gdxVersion") {
    2. exclude group: 'com.badlogicgames.gdx', module: 'gdx-backend-lwjgl'
    3. }

    The cause of this is described here.

Desktop (LWJGL)

In version 1.10.1, libGDX switched its default desktop backend to LWJGL 3. If you want to upgrade, please take a look here.

Click here to show the old LWJGL backend instructions

Opening the DesktopLauncher.java class in my-gdx-game shows the following:

  1. package com.me.mygdxgame;
  2. import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
  3. import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
  4. public class DesktopLauncher {
  5. public static void main(String[] args) {
  6. LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
  7. cfg.title = "my-gdx-game";
  8. cfg.useGL30 = false;
  9. cfg.width = 480;
  10. cfg.height = 320;
  11. new LwjglApplication(new MyGdxGame(), cfg);
  12. }
  13. }

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

Common issues:

  • When using a JDK of version 8 or later, an “illegal reflective access” warning is shown. This is nothing to be worried about. If it bothers you, downgrade the used JDK or switch to the LWJGL 3 backend.

  • If an error like Process 'command 'C:/.../java.exe'' finished with non-zero exit value -1 is shown, this can safely be ignored. A workaround is disabling forceExit: config.forceExit = false;.

Android

Game Activity

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

  1. package com.me.mygdxgame;
  2. import android.os.Bundle;
  3. import com.badlogic.gdx.backends.android.AndroidApplication;
  4. import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
  5. public class MainActivity extends AndroidApplication {
  6. @Override
  7. public void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
  10. initialize(new MyGdxGame(), cfg);
  11. }
  12. }

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, the AndroidApplication.initialize() method is called, passing in the ApplicationListener, MyGdxGame)\ as well as the configuration. Refer to the AndroidApplicationConfiguration Javadocs for 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.

Game Fragment

A libGDX game can be hosted in an Android Fragment instead of using a complete Activity. This allows it to take up a portion of the screen in an Activity or be moved between layouts. To create a libGDX fragment, subclass AndroidFragmentApplication and implement the onCreateView() with the following initialization:

  1. @Override
  2. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  3. return initializeForView(new MyGdxGame());
  4. }

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

  1. Add AndroidX Fragment 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 the 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:

  1. // 2. Change AndroidLauncher activity to extend FragmentActivity, not AndroidApplication
  2. // 3. Implement AndroidFragmentApplication.Callbacks on the AndroidLauncher activity
  3. public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks
  4. {
  5. @Override
  6. protected void onCreate (Bundle savedInstanceState)
  7. {
  8. super.onCreate(savedInstanceState);
  9. // 6. Finally, replace the AndroidLauncher activity content with the libGDX Fragment.
  10. GameFragment fragment = new GameFragment();
  11. FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
  12. trans.replace(android.R.id.content, fragment);
  13. trans.commit();
  14. }
  15. // 4. Create a Class that extends AndroidFragmentApplication which is the Fragment implementation for libGDX.
  16. public static class GameFragment extends AndroidFragmentApplication
  17. {
  18. // 5. Add the initializeForView() code in the Fragment's onCreateView method.
  19. @Override
  20. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  21. { return initializeForView(new MyGdxGame()); }
  22. }
  23. @Override
  24. public void exit() {}
  25. }

Manifest configuration

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.me.mygdxgame">
  4. <application
  5. android:icon="@drawable/ic_launcher"
  6. android:label="@string/app_name" >
  7. <activity
  8. android:name=".MainActivity"
  9. android:label="@string/app_name"
  10. android:screenOrientation="landscape"
  11. android:configChanges="keyboard|keyboardHidden|orientation">
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. </application>
  18. </manifest>

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.

Permissions

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:

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

Users are generally suspicious of applications with many permissions, so choose 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 in AndroidApplicationConfiguration (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

A libGDX core application can also be used as an Android Live Wallpaper. The project setup is very similar to an Android game, but AndroidLiveWallpaperService is used in place of AndroidApplication. Live Wallpapers are Android Services, not Activities.

Note: Due to synchronization issues, you cannot combine games and live wallpapers in the same app. However, Live Wallpapers and Screen Savers can safely coexist in the same app.

First, extend AndroidLiveWallpaperService and override onCreateApplication() (instead of onCreate() like you would do with a game Activity):

  1. public class MyLiveWallpaper extends AndroidLiveWallpaperService {
  2. @Override
  3. public void onCreateApplication() {
  4. AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
  5. initialize(new MyGdxGame(), cfg);
  6. }
  7. }

You can optionally subscribe to Live Wallpaper-specific events by implementing AndroidWallpaperListener with your ApplicationListener class. AndroidWallpaperListener is not available from the core module, so you can either follow the strategy outlined in Interfacing With Platform-Specific Code, or you can manage it just from the android module by subclassing your ApplicationListener like this:

  1. public class MyLiveWallpaper extends AndroidLiveWallpaperService {
  2. static class MyLiveWallpaperListener extends MyGdxGame implements AndroidWallpaperListener {
  3. @Override
  4. public void offsetChange (float xOffset, float yOffset, float xOffsetStep,
  5. float yOffsetStep, int xPixelOffset, int yPixelOffset) {
  6. // Called when the home screen is scrolled. Not all launchers support this.
  7. }
  8. @Override
  9. public void previewStateChange (boolean isPreview) {
  10. // Called when switched between being previewed and running as the wallpaper.
  11. }
  12. @Override
  13. public void iconDropped (int x, int y) {
  14. // Called when an icon is dropped on the home screen.
  15. }
  16. }
  17. @Override
  18. public void onCreateApplication() {
  19. AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
  20. initialize(new MyLiveWallpaperListener(), cfg);
  21. }
  22. }

Coming in libGDX 1.9.12, or available from -SNAPSHOT now, you can also report the dominant colors of the wallpaper to the OS. Starting with Android 8.1, this is used by some Android launchers and lock screens for styling, such as changing the text color of the clock. You can create a method like this to report the colors, and access it from the core module using the strategy from Interfacing With Platform-Specific Code:

  1. public void notifyColorsChanged (Color primaryColor, Color secondaryColor, Color tertiaryColor) {
  2. Application app = Gdx.app;
  3. if (Build.VERSION.SDK_INT >= 27 && app instanceof AndroidLiveWallpaper) {
  4. ((AndroidLiveWallpaper) app).notifyColorsChanged(primaryColor, secondaryColor, tertiaryColor);
  5. }
  6. }

In additional to the service class, you must also create an xml file in the Android res/xml directory to define some Live Wallpaper properties: its thumbnail and description shown in the wallpaper picker, and an optional settings Activity. Let’s call this file livewallpaper.xml.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <wallpaper
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:thumbnail="@drawable/ic_launcher"
  5. android:description="@string/description"
  6. android:settingsActivity="com.mypackage.MyLiveWallpaperSettingsActivity"/>

Finally, you’ll need to add things to your AndroidManifest.xml files. Here’s an example for a Live Wallpaper with a simple settings Activity. The key elements here are the uses-feature and service blocks. The label and icon set on the service appear in the Android application settings. The settings Activity and the Live Wallpaper service must both be set with exported true so they can be accessed by the Live Wallpaper picker.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.mypackage">
  4. <uses-feature android:name="android.software.live_wallpaper" />
  5. <application android:icon="@drawable/icon" android:label="@string/app_name">
  6. <activity android:name=".MyLiveWallpaperSettingsActivity"
  7. android:label="@string/app_name"
  8. android:exported="true" />
  9. <service android:name=".LiveWallpaper"
  10. android:label="@string/app_name"
  11. android:icon="@drawable/icon"
  12. android:exported="true"
  13. android:permission="android.permission.BIND_WALLPAPER">
  14. <intent-filter>
  15. <action android:name="android.service.wallpaper.WallpaperService" />
  16. </intent-filter>
  17. <meta-data android:name="android.service.wallpaper"
  18. android:resource="@xml/livewallpaper" />
  19. </service>
  20. </application>
  21. </manifest>

Live Wallpapers have some limitations concerning touch input. In general only one pointer will be reported. If you want full multi-touch events you can set the AndroidApplicationConfiguration.getTouchEventsForLiveWallpaper field to true.

Screen Savers (aka Daydreams)

A libGDX core application can also be used as an Android Screen Saver. Screen Savers were once known as Daydreams, so many of the related classes have the term “Daydream” in their names. Screen Savers have no relation to Google’s Daydream VR platform.

The project setup is very similar to an Android game, but AndroidDaydream is used in place of AndroidApplication. Screen Savers are Android Services, not Activities.

First, extend AndroidDaydream and override onAttachedToWindow() (instead of onCreate() like you would do with a game Activity). It must call through to super. You can also call setInteractive() from this method to enable/disable touch. A non-interactive Screen Saver immediately closes when the screen is touched.

  1. public class MyScreenSaver extends AndroidDaydream {
  2. @Override
  3. public void onAttachedToWindow() {
  4. super.onAttachedToWindow();
  5. setInteractive(true);
  6. AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
  7. initialize(new MyGdxGame(), cfg);
  8. }
  9. }

In additional to the service class, you must also create an xml file in the Android res/xml directory to define the only Screensaver setting: an optional settings Activity. Let’s call this file screensaver.xml.

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <dream xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:settingsActivity="com.badlogic.gdx.tests.android/.MyScreenSaverSettingsActivity" />

Finally, you’ll need to add things to your AndroidManifest.xml files. Here’s an example for a Screen Saver with a simple settings Activity. Note that a settings Activity is optional. The key element is the service block. The settings Activity and the Screen Saver service must both be set with exported true so they can be accessed by the Screen Saver picker.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.mypackage">
  4. <application android:icon="@drawable/icon" android:label="@string/app_name">
  5. <activity android:name=".MyScreenSaverSettingsActivity"
  6. android:label="@string/app_name"
  7. android:exported="true" />
  8. <service android:name=".MyScreenSaver"
  9. android:label="@string/app_name"
  10. android:icon="@drawable/icon"
  11. android:exported="true" >
  12. <intent-filter>
  13. <action android:name="android.service.dreams.DreamService" />
  14. <category android:name="android.intent.category.DEFAULT" />
  15. </intent-filter>
  16. <meta-data android:name="android.service.dream"
  17. android:resource="@xml/screensaver" />
  18. </service>
  19. </application>
  20. </manifest>

iOS/Robovm

To come..

HTML5/GWT

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

  1. package com.me.mygdxgame.client;
  2. import com.me.mygdxgame.MyGdxGame;
  3. import com.badlogic.gdx.ApplicationListener;
  4. import com.badlogic.gdx.backends.gwt.GwtApplication;
  5. import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
  6. public class GwtLauncher extends GwtApplication {
  7. @Override
  8. public GwtApplicationConfiguration getConfig () {
  9. GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(480, 320);
  10. return cfg;
  11. }
  12. @Override
  13. public ApplicationListener createApplicationListener () {
  14. return new MyGdxGame();
  15. }
  16. }

The main entry-point is composed of two methods, GwtApplication.getConfig() and GwtApplication.createApplicationListener(). The former has to return a GwtApplicationConfiguration instance, which specifies various configuration settings for the HTML5 application. The GwtApplication.createApplicatonListener() method returns the ApplicationListener 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:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
  3. <module>
  4. <inherits name='com.badlogic.gdx.backends.gdx_backends_gwt' />
  5. <inherits name='MyGdxGame' />
  6. <entry-point class='com.me.mygdxgame.client.GwtLauncher' />
  7. <set-configuration-property name="gdx.assetpath" value="../my-gdx-game-android/assets" />
  8. </module>

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:

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

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 the GwtApplication.getPreloaderCallback() method (GwtLauncher in the above example).

From 1.9.10 on, the following code changes the colors of the progress bar and the displayed logo to a file placed within your webapp folder:

  1. @Override
  2. public Preloader.PreloaderCallback getPreloaderCallback() {
  3. return createPreloaderPanel(GWT.getHostPageBaseURL() + "preloadlogo.png");
  4. }
  5. @Override
  6. protected void adjustMeterPanel(Panel meterPanel, Style meterStyle) {
  7. meterPanel.setStyleName("gdx-meter");
  8. meterPanel.addStyleName("nostripes");
  9. meterStyle.setProperty("backgroundColor", "#ffffff");
  10. meterStyle.setProperty("backgroundImage", "none");
  11. }

Prior to 1.9.10, it is best to copy all getPreloaderCallback() content from libGDX’ sources and adjust it to your needs.

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.

Prev | Next