Singleton应用程序类

Singleton应用程序类

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

问题描述

所以在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 Singleton,并且作为单例,不能包含参数.

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.

-

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

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 Singleton应用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:08