Static way to get 'Context' in Android?

前端 未结 19 2755
猫巷女王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:27

    in Kotlin, putting Context/App Context in companion object still produce warning Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

    or if you use something like this:

        companion object {
            lateinit var instance: MyApp
        }
    

    It's simply fooling the lint to not discover the memory leak, the App instance still can produce memory leak, since Application class and its descendant is a Context.

    Alternatively, you can use functional interface or Functional properties to help you get your app context.

    Simply create an object class:

    object CoreHelper {
        lateinit var contextGetter: () -> Context
    }
    

    or you could use it more safely using nullable type:

    object CoreHelper {
        var contextGetter: (() -> Context)? = null
    }
    

    and in your App class add this line:

    
    class MyApp: Application() {
    
        override fun onCreate() {
            super.onCreate()
            CoreHelper.contextGetter = {
                this
            }
        }
    }
    

    and in your manifest declare the app name to . MyApp

    
        

    When you wanna get the context simply call:

    CoreHelper.contextGetter()
    
    // or if you use the nullable version
    CoreHelper.contextGetter?.invoke()
    

    Hope it will help.

提交回复
热议问题