Jaberish
Jaberish

Reputation: 13

Dispose libGDX resources on game close?

I'm using libGDX and dispose my resources when I do not need them anymore to free up RAM. Do I need to manually dispose resources when the game ends? Or is this done automatically by the Android (or libGDX)?

Upvotes: 1

Views: 371

Answers (2)

Tenfour04
Tenfour04

Reputation: 93882

Yes, you must, or the native memory associated with all those objects will all leak. Closing an Activity (which is what hosts a Libgdx game) in Android does not close the entire Application, and so the memory will not be reclaimed by the OS and you will have lost all your references to the objects that can be disposed.

Upvotes: 1

m.antkowicz
m.antkowicz

Reputation: 13581

The truth is that some of object need to be disposed manually - due to reference they are for example:

  • Pixmap
  • Texture
  • Bitmap

and many others you will find here.

To make it easier to manage your assets you should use AssetManager. The way how to use is desribed here, but the general pattern is:

  1. Creating AssetManager instance
  2. Loading assets to AssetManager instance
  3. Using resources getting them from mentioned object
  4. Disposing the AssetManager instance at the end of application life

The example code:

    AssetManager assetManager = new AssetManager();

    assetManager.load("data/mytexture.png", Texture.class);

    assetManager.finishLoading(); //loading resources to asset manager is asynchrous! you can also use .update() method - find it in the reference

    ...

    Texture tex = assetManager.get("data/mytexture.png", Texture.class); //use the asset manager to obtain texture

    ...

    assetManager.clear(); //disposing asset manager with all its resources - you can also use .dispose() method

Upvotes: 0

Related Questions