In my android application, I'm overriding Application class like below.
public class MyApplication extends Application {
private static MyApplication instance = null;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance(){
return instance;
}
}
I'm doing this to keep my applicationcontext releted stuf(like database connection which I am creating with applicationcontext and using on entire application) between configuration changes and to access application instance without needing activity object(Activity.getApplication()
).
Now the question is, is there any down sides of keeping application's static instance? I mean, according to my understanding, after Application.onCreate()
gets called(which should only happens once), MyApplication.getInstance()
should never return null. Is this true?
Also is there any way on Android to start Application instance more than once(without killing the old one)? If there is, what my static instance
variable will points to after second instance stated? I'm guessing, because they will be different processes, each points to it's own application but i can't be sure.
PS: I am not asking about overriding Application class, I already know Dianne Hackborn(an Android framework engineer) says there is no need to override Application class, using Singletons instead should be fine. The question is more about application lifecycle and keeping static variable.
The short answer is, yes it is safe.
Before any other components in your application startup, the application class is loaded and
onCreate()
is invoked, so in every component of your application (Activity, Service, Database, etc) you are guaranteed to have an instance.The other type of safety in terms of a memory leak is also fine consdering you are using this static throughout your app. The only thing to keep in mind is that the static will be in memory as long as the application process is running.