所以在android中,我想让我的应用程序类是一个单身人士。Kotlin SingleTon应用程序类
使其像这样:
object MyApplication: Application(){}
将无法正常工作。以下误差修改是在运行时抛出:
java.lang.IllegalAccessException: private com....is not accessible from class android.app.Instrumentation.
这样做也是不可能的:
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_
}
}
那么,如何才能让我的应用程序类无处不在我的应用程序的实例,想用MyApp.instance()
代替(applicationContext as MyApp)
。
另外一个解释,为什么我想要这样的:我有我的应用程序中的类,例如,一个SharedPreference Singleton用上下文初始化,并且作为其单例,不能有参数。
这看起来不错@nitrico,但我无法获得'val Context.myApp:MyApp get()= applicationContext作为MyApp的部分工作。你可以进一步了解更多细节吗?这条线路需要去哪里以及如何在另一个班级访问? – shredder