What is the lifecycle of a static variable shared between Activities?

Jack :

I have a BaseActivity and multiple Activities that extends it.

The BaseActivity has a static variable, which makes it shared between descendant Activities (they all share the same instance of it).

The static variable is initialised ONLY by MainActivity (that extends BaseActivity).

The MainActivity explicitly registers for a BroadcastReceiver.

The BroadcastReceiver changes the values in the static variable.

I want to make sure if the system killed MainActivity (for low memory, for example), the static variable will be reset and set to null.

As I said, MainActivity shares the static var with other Activities, and it solely owns the BroadcastReceiver and it's the one initialises the static var.

Without the BroadcastReceiver the static variable data will be unreliable.

Now you have the whole scenario. Let's get into the questions:

What is the lifecycle of the shared static var in this case?

Does Android (in case of low memory) destroys individual activities or does it destroy my whole app (whole activities)?

  • If it destroys my app entirely and reset the static var that would be acceptable, my worries that it would destroy MainActivity alone and unregister the BroadcastReceiver, yet it keeps the static var (Which will become unreliable).

If Android could destroy MainActivity alone and keep the static var, how could I get notified or be aware of that next time MainActivity starts so I can reload the values inside the static var?

For sorry I can't rely on onDestroy() within MainActivity to set the static var to null, as you know it's not guaranteed to be called in case Android destroyed the activity in low memory.

Onik :

I want to make sure if the System killed MainActivity (For low memory for example), the static variable will be reset and set to null. What is the lifecycle of the shared static var in this case?

The static variable will be reset to null ONLY when all the other Activities that extend BaseActivity will be killed (cause it's already been set != null by MainActivity and/or BroadcastReceiver). Since all your Activities extend BaseActivity, the variable reset are going to happen upon the whole process termination.

Does Android (In case of low memory) destroys individual activities or does it destroy my whole app (Whole activities)?

In this case Android destroys whole app process.

If Android could destroy MainActivity alone and keep the static var, how could I get notified or be aware of that next time MainActivity starts so I can reload the values inside the static var?

Use SharedPreferences if applicable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102778&siteId=1