Application class
The Application class represents the whole app. This is the first class to be initialized when app starts.
The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.
Most methods of Application are inherited from Context class.
custom application
You can create custom app object by extending Application class.
1. Define own class.
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
_appContext = applicationContext
// required initialization logic here
}
override fun onConfigurationChanged ( newConfig : Configuration ) {
super.onConfigurationChanged(newConfig)
// ... do something
}
override fun onLowMemory() {
super.onLowMemory()
// ... do something
}
companion object {
private lateinit var _appContext: Context
@JvmStatic
val appContext
get() = _appContext
}
}
public class MyApp extends Application {
private static Context appContext;
public static Context getAppContext() {
return appContext;
}
@Override
public void onCreate() {
super.onCreate();
appContext = getApplicationContext();
// required initialization logic here
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// ... do something
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}
2. Specify the android:name property in the the application node in AndroidManifest.xml
<application
android:name=".MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name"
...>
Note. In example above we define application context as static member. However android doc recommends to initialize your singletons with context right away. For example, by getApplicationContext() method of activity / service / application.
Note. Don't do long task in the onCreate method in main thread. Otherwise user will see black screen before first activity.