Static way to get 'Context' in Android?

Andrea Baccega picture Andrea Baccega · Jan 4, 2010 · Viewed 714.2k times · Source

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.

Answer

Rohit Ghatol picture Rohit Ghatol · Feb 25, 2011

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.