I'm currently not happy with my dispose() implementation for a libgdx game for android.
What i'm doing at the moment, is loading all my assets in an assetmanager when my app is launched, pass it around and use the assets.
I tested two different things: First i didnt dispose at all, so when the app is closed via android back or home and reopened everything is working fine and the current screen is displayed correctly. I'm not sure what happens to the assets in this case. They should remain in memory,and can be reused when the app is resumed. But what happens if android kills the app in background. I guess i get a memory leak than ?
So i tried disposing in the onPause() callback and reload the assets in the onResume().Now my screen wasnt rendered anymore, so i think i had to rebuild it completly, cause the assetmanager.get(...) in the scene2d actors contrustors now have to be updated ? So i tried building the scenegraph in the show() method, which didnt work out, cause my gamelogic from which the screen gets its data now threw alot of errors. I worked around that with just restarting from the menu when the user exits the app and resumes, which im not happy with either.
Additionally i create bitmapfonts with FreeTypeFontGenerator on the fly in different parts of my screens, which i dispose() when hiding the screen. So, i guess i have a problem here too, when the app is closed and later destroyed by android ?
You should dispose in the dispose
method of your Game/Screen/ApplicationListener. This is called by Android when the Activity finishes and is the proper place to dispose of all the native memory. It is done automatically.
You cannot expect to be able to reuse loaded textures after an Activity finishes and a new one is created, so make sure your assets are loaded in the create
method of your Game/ApplicationListener, not resume
.
A memory leak will not happen as a result of Android killing your application in the background. Android is able to reclaim all memory from your application when it kills it. But if your Activity is closed without your total application being killed, then you will leak stuff that was not properly disposed.
A memory leak in LibGDX happens when you are using any class that implements Disposable, and you don't dispose of it when you're done using it.