Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Application class in Android

Tags:

android

What exactly is the purpose of Application class. what are the benefits of extending it to a custom subclass Why use it ? Can global variables be stored in any other class achieve same goal as Application ?

like image 510
Ahmed Avatar asked Nov 15 '12 15:11

Ahmed


People also ask

What is the purpose of Android app activity?

An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app.

What is the application class in Android 1 point?

What is the application class in android? Explanation : Application class is the base class for any android application.

What is the meaning of Android application?

An Android app is a software application running on the Android platform. Because the Android platform is built for mobile devices, a typical Android app is designed for a smartphone or a tablet PC running on the Android OS.


1 Answers

Nice question !

Your application is a context that is always running while your activities and services are running.

It is also the first context to be created and the last to be destroyed. Thus, it surrounds the life cycle of your app.

You can use the application class as a way to share data or components (for dependency injection for instance). For instance if you want to share a singleton between activities, you can create the instance in the application class and provide a getter, then all other contexts can get the singleton via

((cast to your class)getApplicationContext()).getFoo();

There may be some use cases where you need to do stuff before even your first activity is launched, then do it in the onCreate method of the application class.

On the other hand, you should never relie on the onDestroy method of the Application class, as it is not always called. There is no contract for that on Android.

But this is rare and, usually, you don't need to override the application class though. Dependency injection can be achieved in other ways by RoboGuice or Dagger for instance.

like image 112
Snicolas Avatar answered Nov 16 '22 03:11

Snicolas