Static way to get 'Context' in Android? Static way to get 'Context' in Android? android android

Static way to get 'Context' in Android?


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.


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!


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