Static way to get 'Context' in Android?

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

    If you're open to using RoboGuice, you can have the context injected into any class you want. Here's a small sample of how to do it with RoboGuice 2.0 (beta 4 at time of this writing)

    import android.content.Context;
    import android.os.Build;
    import roboguice.inject.ContextSingleton;
    
    import javax.inject.Inject;
    
    @ContextSingleton
    public class DataManager {
        @Inject
        public DataManager(Context context) {
                Properties properties = new Properties();
                properties.load(context.getResources().getAssets().open("data.properties"));
            } catch (IOException e) {
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:24

    You can use the following:

    MainActivity.this.getApplicationContext();
    

    MainActivity.java:

    ...
    public class MainActivity ... {
        static MainActivity ma;
    ...
        public void onCreate(Bundle b) {
             super...
             ma=this;
             ...
    

    Any other class:

    public ...
        public ANY_METHOD... {
             Context c = MainActivity.ma.getApplicationContext();
    
    0 讨论(0)
  • 2020-11-21 07:24

    I think you need a body for the getAppContext() method:

    public static Context getAppContext()
       return MyApplication.context; 
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-11-21 07:25

    Kotlin way:

    Manifest:

    <application android:name="MyApplication">
    
    </application>
    

    MyApplication.kt

    class MyApplication: Application() {
    
        override fun onCreate() {
            super.onCreate()
            instance = this
        }
    
        companion object {
            lateinit var instance: MyApplication
                private set
        }
    }
    

    You can then access the property via MyApplication.instance

    0 讨论(0)
  • 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

    
        <application
                android:name=".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.

    0 讨论(0)
提交回复
热议问题