本文介绍了Kotlin 单例应用程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在 android 中,我想让我的应用程序类成为单例.

So in android i want to make my application class a singleton.

让它像这样:

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.

这样做也是不可能的:

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).

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).

还要解释为什么我想要这个:我的应用程序中有类,例如,一个用上下文初始化的 SharedPreference 单例,作为它的单例,不能有参数.

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.

推荐答案

如果您想使用它来访问一些静态属性,您就拥有了:您将只有一个应用程序实例,因此只需使用您为班级提供的名称即可.不要担心它不是真正的单例,你可以用同样的方式使用它.

If you want to use it to access some static properties you have there: You will only have one instance of your Application, so simply use the name you gave to the class. Don't worry about it not being an actual singleton, you can use it the same way.

示例:

class MyApp : Application() {

    companion object {
        const val CONSTANT = 12
        lateinit var typeface: Typeface
    }

    override fun onCreate() {
        super.onCreate()
        typeface = Typeface.createFromAsset(assets, "fonts/myFont.ttf")
    }

}

然后你可以在你的应用程序的任何地方使用 MyApp.CONSTANTMyApp.typeface.

Then you can use MyApp.CONSTANT and MyApp.typeface anywhere in your app.

-

如果您想要将其用作应用程序上下文,您可以为 Context 创建一个扩展属性:

If what you want is to use it as an application context you can create an extension property for Context:

val Context.myApp: MyApp
        get() = applicationContext as MyApp

然后你可以使用 myApp 来获取你有上下文的任何地方的应用上下文.

Then you can use myApp to get the the application context anywhere you have a context.

这篇关于Kotlin 单例应用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:23