user4959397
user4959397

Reputation:

Android what if static final class gets unload (hide and show application)

Hello I'm working on a game for android. And I'm not shure how to handle classes if the user goes for example to the phones menu and back in to the game.

I heard if a android device needs memory, classes getting unload also static final classes.

Now for example I created the class Player as a singleton class should I reassemble the class every time the game gets shown again?

What's about static final classes is there a way to reasseble them or are they lost and the game doesn't work propperly until the game gets restarted?

Upvotes: 0

Views: 61

Answers (2)

Gaurav Singh
Gaurav Singh

Reputation: 2320

If a device needs memory then it kills your app process(if it is in background) as a result of which your static final classes as well as singleton gets cleared.

And when you bring back it to foreground it will throw NullPointerException.

Solution: Make your class Parcelable for which you are creating singleton. Follow below link: https://developer.android.com/reference/android/os/Parcelable.html

Then override onSavedInstanceState method wherever you are using singleton and put your class object obtained from singleton in bundle like this: bundle.putParcelable(key,object).

Lastly, you need to restore this object by checking in your onCreate function that if bundle is not null then set singleton object as object obtained from bundle.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006644

I heard if a android device needs memory, classes getting unload also static final classes.

No. The process will be terminated entirely.

Now for example I created the class Player as a singleton class should I reassemble the class every time the game gets shown again?

You need to handle the case where your process will be terminated while it is in the background. You can handle this via some combination of the saved instance state Bundle and persisting data to disk that you need to be able to restore the game to its former state.

Upvotes: 3

Related Questions