So in android i want to make my application class a singleton.
Making it like this:
object MyApplication: Application(){}
won't work. Following erros is thrown at runtime:
java.lang.IllegalAccessException: private com....is not accessible from class android.app.Instrumentation.
Doing this is also not possible:
class MyApp: Application() {
private val instance_: MyApp
init{
instance_ = this
}
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree());
}
}
companion object{
fun getInstance() = instance_
}
}
So how can i get an instance of my application class everywhere in my app, would like to use MyApp.instance()
instead of (applicationContext as MyApp)
.
Also an explanation why i want this: I have classes in my app, for example, a SharedPreference Singleton which is initialised with a context, and as its a singleton, can't have arguments.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…