Ofek Ron Ofek Ron - 9 months ago 41
Android Question

How to get my activity context?

I don't really get the idea behind how this whole thing works really, so if I have some class

that need the context of a class
which extends
, how do i get that context?

I'm searching for a more efficient way then giving the context as a parameter to class
constructor, since for exsmple if class
is going to have millions of instances then we would end up having millions of redundant pointer to
while we should be able somehow to have just one somewhere and a getter function...

Answer Source

You can use Application class(public class in android.application package),that is:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

To use this class do:

public class App extends Application implements OnInitListener {

    private static Context mContext;

    public static Context getContext() {
        return mContext;

    public static void setContext(Context mContext) {
        this.mContext = mContext;



In your manifest:

        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

In Activity B:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {


In class A:

Context c = App.getContext();


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.