Static way to get 'Context' in Android?

前端 未结 19 2589
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  有刺的猬
    2020-11-21 07:07

    Kotlin

    open class MyApp : Application() {
        override fun onCreate() {
            super.onCreate()
            mInstance = this
        }
    
        companion object {
            lateinit var mInstance: MyApp
            fun getContext(): Context? {
                return mInstance.applicationContext
            }
        }
    }
    

    and get Context like

    MyApp.mInstance
    

    or

    MyApp.getContext()
    

提交回复
热议问题