旧行李
2010-01-04 21:15
采纳率: 25%
浏览 460

在 Android 中获得'上下文'的静态方式?

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 each time it changes.

转载于:https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

18条回答 默认 最新

  • 三生石@ 2011-02-25 06:37
    已采纳

    Do this:

    In the Android Manifest file, declare the following.

    <application android:name="com.xyz.MyApplication">
    
    </application>
    

    Then write the class:

    public class MyApplication extends Application {
    
        private static Context context;
    
        public void onCreate() {
            super.onCreate();
            MyApplication.context = getApplicationContext();
        }
    
        public static Context getAppContext() {
            return MyApplication.context;
        }
    }
    

    Now everywhere call MyApplication.getAppContext() to get your application context statically.

    点赞 打赏 评论
  • larry*wei 2010-01-05 00:46

    No, I don't think there is. Unfortunately, you're stuck calling getApplicationContext() from Activity or one of the other subclasses of Context. Also, this question is somewhat related.

    点赞 打赏 评论
  • ℡Wang Yan 2011-08-12 01:07

    It depends on what you are using the context for. I can think of at least one disadvantage to that method:

    If you are trying to create an AlertDialog with AlertDialog.Builder, the Application context won't work. I believe you need the context for the current Activity...

    点赞 打赏 评论
  • 三生石@ 2011-08-18 14:15

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

    public static Context getAppContext()
       return MyApplication.context; 
    
    点赞 打赏 评论
  • larry*wei 2012-02-29 14:46

    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) {
            }
        }
    }
    
    点赞 打赏 评论
  • 叼花硬汉 2012-09-19 13:34

    Here is an undocumented way to get an Application (which is a Context) from anywhere in the UI thread. It relies on the hidden static method ActivityThread.currentApplication(). It should work at least on Android 4.x.

    try {
        final Class<?> activityThreadClass =
                Class.forName("android.app.ActivityThread");
        final Method method = activityThreadClass.getMethod("currentApplication");
        return (Application) method.invoke(null, (Object[]) null);
    } catch (final ClassNotFoundException e) {
        // handle exception
    } catch (final NoSuchMethodException e) {
        // handle exception
    } catch (final IllegalArgumentException e) {
        // handle exception
    } catch (final IllegalAccessException e) {
        // handle exception
    } catch (final InvocationTargetException e) {
        // handle exception
    }
    

    Note that it is possible for this method to return null, e.g. when you call the method outside of the UI thread, or the application is not bound to the thread.

    It is still better to use @RohitGhatol's solution if you can change the Application code.

    点赞 打赏 评论
  • 喵-见缝插针 2013-02-26 10:50

    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 :)

    点赞 打赏 评论
  • 谁还没个明天 2013-04-06 17:25

    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();
    
    点赞 打赏 评论
  • 七度&光 2014-12-30 19:20

    I use a variation of the Singleton design pattern to help me with this.

    import android.app.Activity;
    import android.content.Context;
    
    public class ApplicationContextSingleton {
        private static Activity gContext;
    
        public static void setContext( Activity activity) {
            gContext = activity;
        }
    
        public static Activity getActivity() {
            return gContext;
        }
    
        public static Context getContext() {
            return gContext;
        }
    }
    

    I then call ApplicationContextSingleton.setContext( this ); in my activity.onCreate() and ApplicationContextSingleton.setContext( null ); in onDestroy();

    点赞 打赏 评论
  • 北城已荒凉 2015-01-19 09:09

    The majority of apps that want a convenient method to get the application context create their own class which extends android.app.Application.

    GUIDE

    You can accomplish this by first creating a class in your project like the following:

    import android.app.Application;
    import android.content.Context;
    
    public class App extends Application {
    
        private static Application sApplication;
    
        public static Application getApplication() {
            return sApplication;
        }
    
        public static Context getContext() {
            return getApplication().getApplicationContext();
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            sApplication = this;
        }
    }
    

    Then, in your AndroidManifest you should specify the name of your class in the AndroidManifest.xml’s tag:

    <application 
        ...
        android:name="com.example.App" >
        ...
    </application>
    

    You can then retrieve the application context in any static method using the following:

    public static void someMethod() {
        Context context = App.getContext();
    }
    

    WARNING

    Before adding something like the above to your project you should consider what the documentation says:

    There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.


    REFLECTION

    There is also another way to get the application context using reflection. Reflection is often looked down upon in Android and I personally think this should not be used in production.

    To retrieve the application context we must invoke a method on a hidden class (ActivityThread) which has been available since API 1:

    public static Application getApplicationUsingReflection() throws Exception {
        return (Application) Class.forName("android.app.ActivityThread")
                .getMethod("currentApplication").invoke(null, (Object[]) null);
    }
    

    There is one more hidden class (AppGlobals) which provides a way to get the application context in a static way. It gets the context using ActivityThread so there really is no difference between the following method and the one posted above:

    public static Application getApplicationUsingReflection() throws Exception {
        return (Application) Class.forName("android.app.AppGlobals")
                .getMethod("getInitialApplication").invoke(null, (Object[]) null);
    } 
    

    Happy coding!

    点赞 打赏 评论
  • 7*4 2016-02-23 14:20

    If you for some reason want Application context in any class, not just those extending application/activity, maybe for some factory or helper classes. You can add the following singleton to your app.

    public class GlobalAppContextSingleton {
        private static GlobalAppContextSingleton mInstance;
        private Context context;
    
        public static GlobalAppContextSingleton getInstance() {
            if (mInstance == null) mInstance = getSync();
            return mInstance;
        }
    
        private static synchronized GlobalAppContextSingleton getSync() {
            if (mInstance == null) mInstance = 
                    new GlobalAppContextSingleton();
            return mInstance;
        }
    
        public void initialize(Context context) {
            this.context = context;
        }
    
        public Context getApplicationContext() {
            return context;
        }
    }
    

    then initialize it in your application class's onCreate with

    GlobalAppContextSingleton.getInstance().initialize(this);
    

    use it anywhere by calling

    GlobalAppContextSingleton.getInstance().getApplicationContext()
    

    I don't recommend this approach to anything but application context however. As it can cause memory leaks.

    点赞 打赏 评论
  • ℙℕℤℝ 2016-08-16 05:36

    Assuming we're talking about getting the Application Context, I implemented it as suggested by @Rohit Ghatol extending Application. What happened then, it's that there's no guarantee that the context retrieved in such a way will always be non-null. At the time you need it, it's usually because you want to initialize an helper, or get a resource, that you cannot delay in time; handling the null case will not help you. So I understood I was basically fighting against the Android architecture, as stated in the docs

    Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.

    and explained by Dianne Hackborn

    The only reason Application exists as something you can derive from is because during the pre-1.0 development one of our application developers was continually bugging me about needing to have a top-level application object they can derive from so they could have a more "normal" to them application model, and I eventually gave in. I will forever regret giving in on that one. :)

    She is also suggesting the solution to this problem:

    If what you want is some global state that can be shared across different parts of your app, use a singleton. [...] And this leads more naturally to how you should be managing these things -- initializing them on demand.

    so what I did was getting rid of extending Application, and pass the context directly to the singleton helper's getInstance(), while saving a reference to the application context in the private constructor:

    private static MyHelper instance;
    private final Context mContext;    
    
    private MyHelper(@NonNull Context context) {
        mContext = context.getApplicationContext();
    }
    
    public static MyHelper getInstance(@NonNull Context context) {
        synchronized(MyHelper.class) {
            if (instance == null) {
                instance = new MyHelper(context);
            }
            return instance;
        }
    }
    

    the caller will then pass a local context to the helper:

    Helper.getInstance(myCtx).doSomething();
    

    So, to answer this question properly: there are ways to access the Application Context statically, but they all should be discouraged, and you should prefer passing a local context to the singleton's getInstance().


    For anyone interested, you can read a more detailed version at fwd blog

    点赞 打赏 评论
  • from.. 2016-12-13 08:29

    According to this source you can obtain your own Context by extending ContextWrapper

    public class SomeClass extends ContextWrapper {
    
        public SomeClass(Context base) {
          super(base);
        }
    
        public void someMethod() {
            // notice how I can use "this" for Context
            // this works because this class has it's own Context just like an Activity or Service
            startActivity(this, SomeRealActivity.class);
    
            //would require context too
            File cacheDir = getCacheDir();
        }
    }
    

    JavaDoc for ContextWrapper

    Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

    点赞 打赏 评论
  • ℙℕℤℝ 2018-03-14 21:02

    If you don't want to modify the manifest file, you can manually store the context in a static variable in your initial activity:

    public class App {
        private static Context context;
    
        public static void setContext(Context cntxt) {
            context = cntxt;
        }
    
        public static Context getContext() {
            return context;
        }
    }
    

    And just set the context when your activity (or activities) start:

    // MainActivity
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Set Context
        App.setContext(getApplicationContext());
    
        // Other stuff
    }
    

    Note: Like all other answers, this is a potential memory leak.

    点赞 打赏 评论
  • 10.24 2018-05-23 12:42

    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

    点赞 打赏 评论
  • 游.程 2018-06-17 16:29

    I have tested all here described suggestion and can say:

    if i use follow code:

    public class App extends Application {
        private static Context context;
        public void onCreate() {
            super.onCreate();
            context = getApplicationContext();
        }
    
        public static Context getAppContext() {
            return context;
        }
    }
    

    i get in the Studio 3 an error message:

    Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run).

    But if i use follow code:

    public class App extends Application {
        private static List<Context> context = new ArrayList<>();
    
        @Override
        public void onCreate() {
            super.onCreate();
            context.add(0, getApplicationContext());
        }
    
        public static Context getAppContext() {
            return context.get(0);
        }       
    } 
    

    it work's fine without any errors.

    点赞 打赏 评论
  • Memor.の 2018-07-12 13:04

    Rohit's answer seems correct. However, be aware that AndroidStudio's "Instant Run" depends on not having static Context attributes in your code, as far as I know.

    点赞 打赏 评论
  • In 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()
    
    点赞 打赏 评论

相关推荐 更多相似问题