Application Class Lifecycle in Android - android

To maintain global variables, the Application class is extended. What happens to these variables when the application is put in the background and at some point, the OS wants to free up the resources? If the onTrimMemory() call is ignored, then does that mean that all of the variables are preserved? Unlike the Activity, which may have to rebuild some of its state.
Thanks,
Gary

To maintain global variables, the Application class is extended
You are also welcome to use classic Java static data members.
What happens to these variables when the application is put in the background and at some point, the OS wants to free up the resources?
The only "resources" that "the OS wants to free up" will be your entire process. Your static data members or other singletons (like a custom Application, or your ContentProvider instances) will remain in memory until such time as Android terminates your process.
If the onTrimMemory() call is ignored, then does that mean that all of the variables are preserved?
Yes, until such time as Android terminates your process.

Related

How long do classes with static methods live in Android?

This is a follow up question to one of my previous questions.
I have a LoadingActivity which loads some graphics needed by all Activities and store it into a static class. I try to not load the LoadingActivity over again when pressing HOME and resume the app since it takes a lot of memory and runs out of it after several times whereby the graphics are already loaded, so no need to start the LoadingActivity again.
My question is, how long does the static class live? Can I rely on it's availability after resuming the app, or may it be here since Android kills it due to memory issues or is it always here as long as the vm runs (that means as long as the phone is running)?
As Simon points out, "static class" means different things in different languages, and Java does not have anything quite like the static classes in some other languages. But I don't think that's what you're talking about. You seem to be asking whether objects referenced by strong static references can be garbage collected. If so, the answer is no.
A class is represented by an object of class Class which is reachable via its ClassLoader. Anything referenced by the Class will therefore be reachable as long as the ClassLoader is reachable, which in the case of the system classloader is as long as the Java/Dalvik VM exists. But that is not as long as the phone runs, since an independent VM is created for each app. The entire process and VM in which an app is running may be killed whenever the app is in the background. When you return to the app, its classes will be reloaded.
If static fields are really the best choice, as opposed to a ContentProvider or foregound Service, then every time your app resumes you will need to check if the static references have been initialized and re-initialize them if they are null.

Saving global state in an Android app

What's the best way to save any changes to global state, that would be lost if the process was killed due to low memory etc?
For activities we have onSaveInstanceState() which allows state to be saved when needed.
I would like something similar for global state. Our Application class holds a references to many objects that can be simply reloaded in onCreate() when the app next starts. But we also change the state of some of those objects, and require these changes to be maintained through the app being killed due to low memory etc.
We could of course persist every time changes are made to the objects in memory. But this would be very wasteful.
My current thought is to use onActivitySaveInstanceState() and keep a dirty flag to know only to call it once. But this adds complexity and probably isn't what this method was intended for.
This cannot be a particularly uncommon requirement, but most of the resources on the net focus on just Activity lifecycle. I'd be pleased to learn of a better approach.
There is no concept of Global State and I actually think that you don't need it at all. An app consists of several independent parts which have their own "state". Thus each part is responsible for its own state. For instance, a fragment which shows particular data knows where to get this data and what to do if there is no such data. An activity which shows user settings knows where to get user settings, how to update it and so on. Both of these parts know what to do when lifecycle methods are calling.
You can always store values in your Application class. On a high level, this is very simple, you create a custom MyCustomApplication, that extends the Android Application class. The Applicaiton class only lives, while the App is in scope (including when it's in the background, which is somewhat unpredictable in Android).
Then you would can access this using the getContext().getApplication()
The implementation details are more complex, and you really should extend the Applicaiton into a Singleton, as described in this SO post: Singletons vs. Application Context in Android?

Android: Is it safely to store global listeners in global list?

Sorry for my English
I have some class that has static (== global) methods such as setListener(), removeListener(). It stores quite few listeners (which are global) and these listeners take very low memory.
But what will happen if the system kills my app's activity because of the lack memory for other application?
Could happen that the system will remove these global listeners?
If the system kills your app, it kills the VM - static variables are lost.
Depending on what you're doing, you probably don't want to register short lived listeners in a static way.

Extending the Application Class & Good Practices

I have been told recently that extending the Application Class in order to use it as a Singleton was a bad practice but without any explanation.
So what are the potentials problem behind the use of this class ? I have seen it used in many projects.
Also, if using the Application Class is a bad idea, what are the alternatives to store application level variables ?
Using a Singleton approach is not really a bad idea, but it may be troublesome in the cases when being used in a multi-threaded environment where one thread sets a value to a variable and the other thread may over-write that value without any notice.
However, in order to keep application level instances/variables, it is suggested to extend Application class and define it in your AndroidManifest.xml as the default one. Since the application's context is created only once (till the application is running and stays in the memory) when you launch that application, so you may define some variables inside that class to make them availabe anywhere in your application's code using public methods.
Moreover, you may use your application class as Singleton too, since its guaranteed to be created only once when launched.
The problem with using a Singleton class, as well as extending the Application class, is that if the application process is killed - which is very likely to happen when the app is left too long in background - the object will lose all your data.
However, using Application class may be a good option in cases when your app is in foreground or does not stay to much in background (although not 100% risk free).
As an alternative, you could save the data into SharedPreferences, or if your object is more complex, save it in a database.
Another option would be to combine both the use of Application, plus SharedPreferences for example. First try to retrieve the variable from Application instance, if the variable is null, then retrieve it from SharedPreferences.

Killed Android service and static variables

Using Android 2.1+. I have a service that gets killed from time to time by the OS (due to memory pressure I guess).
This service maintains some states using static member fields of classes. I'm expecting the static fields to keep their values despite the service being killed and restarted by the OS.
But it seems that it doesn't happen like this. After a restart, static variables are reset to default value.
Is it what is supposed to happen? Should I use another way to keep a persistent state despite kill/restart?
Yes, this is what happens when your service is killed. The program is taken out of memory, and when it's reloaded into memory, the default values for the static variables are all assumed. Put another way, the byte code for your program can't change from execution to execution.
It's generally considered bad from to use static variables to keep state. Try storing them in presistent storage, like a sqlite database.

Categories

Resources