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 ?
The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
From anywhere. Swipe up from the bottom of your screen to the top. If you get All Apps , tap it. Tap the app that you want to open.
Application Not Responding (ANR) errors are triggered when the UI thread of the application is not responding for more than 5 seconds. You can read more about ANRs and diagnosing ANRs in the Android documentation. Additionally, Crashlytics can help pinpoint specific problematic threads.
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With