Static way to get 'Context' in Android?

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

    I just released a jQuery-inspired framework for Android called Vapor API that aims to make app development simpler.

    The central $ facade class maintains a WeakReference (link to awesome Java blog post about this by Ethan Nicholas) to the current Activity context which you can retrieve by calling:

    $.act()
    

    A WeakReference maintains a reference without preventing the garbage collection reclaiming the original object, so you shouldn't have a problem with memory leaks.

    The downside of course is that you run the risk that $.act() could return null. I have not come across this scenario yet though, so it's perhaps just a minimal risk, worth mentioning.

    You can also set the context manually if you are not using VaporActivity as your Activity class:

    $.act(Activity);
    

    Also, much of the Vapor API framework uses this stored context inherently which might mean you needn't store it yourself at all if you decide to use the framework. Check out the site for more information and samples.

    I hope that helps :)

提交回复
热议问题