Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

android - Kotlin Singleton Application Class

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do the same thing you would do in Java, i.e. put the Application instance in a static field. Kotlin doesn't have static fields, but properties in objects are statically accessible.

class MyApp: Application() {

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: MyApp
            private set
    }
}

You can then access the property via MyApp.instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...