Libgdx app.exit() on Android not closing application

ruff1991 picture ruff1991 · Sep 20, 2012 · Viewed 15k times · Source

In my Android app developed with libGDX I use Gdx.app.exit() when the user tries to exit the game. This closes the game, but when the user restarts the app all the Textures are scrambled (beyond the point of using the app). I noticed that if I force close the app from a task-manager, then it will restart properly.

Why does it happen?

Answer

P.T. picture P.T. · Sep 20, 2012

You have rediscovered the mismatch between the lifetime of Java objects (tied to the life of the application process) and the lifetime of texture objects (tied to the life of the OpenGL context which is tied to the visibility of the Activity).

On app "exit", just the Activity is exited, and Android is caching the process in the background. When you "restart" the app Android just starts a new Activity in the same process. In this case the Activity is finding a valid Java Texture object, but the underlying bytes it "points to" in the OpenGL context are gone (since the OpenGL context is invalidated when the Activity is no longer visible).

The fix is to re-load textures on activity creation. You must make sure all your objects that contain textures (and objects that contain objects that contain textures, etc) are tied to the Activity lifecycle. Generally this means avoiding static variables (which are part of the application lifecycle), but you can jump through hoops to invalidate and re-initialize globals if you want.