In the documentation of android.app.Application it says:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given aContextwhich internally usesContext.getApplicationContext()when first constructing the singleton.
But is that right? Or it there is a case for android.app.Application?
The second part of the documentation has its merits. I am not against singletons as such. And using them to modularise your global data is good idea.
But singletons have one problem: they need to be initialised somehow. And that can turn out quite difficult.
The usual way of lazy initialisation has huge concurrency problems. You can find tons o material on this.
Also your getInstance () might need a android.content.Context as parameter. Making it both unwieldy and error prone. It only takes one developer in the team to use an android.app.Activity (aka this) in the getInstance () call the and you have a memory leak and difficult to find sporadic crash.
Remember: Even it you have only one android.app.Activity — it is destroyed and recreated when the device is rotated. Yes there is an option to prevent that. But that makes things only worse. Don't use it unless you really have to.
The next idea would be to initialise all singletons in your main activities onCreate. That would solve concurrency and new developers to the team problem. Also you can use a getInstance () without a parameter by using a separate createInstance (). But beware: there are many cases where where your main activity might not be created: android.content.BroadcastReceiver, android.app.Service or instrumentation tests. Especially the last one! Instrumentation tests can create anything out of order.
Initialising them in all Activities? Sound complicated.
But it all does not need to be like this: We haven android.app.Application.Create (). Guaranteed to be called just once before anything else. No concurrency problems, no need for an if (!initialised), all initialisation done in the right order, and it's this is a context guaranteed to exist als long as the process is running.
And last not least: If needed for your instrumentation tests you can use a MockApplication which initialises your singletons with mock objects.
I hink it does not get much better than this. And this is why all android apps I have worked on subclass android.app.Activity.
Keine Kommentare:
Kommentar veröffentlichen