How to retrieve a context from a non-activity class?

This problem seem to arise a lot in Android development. One solution to obtaining a reference to a specific Context is subclassing the Application and grab a reference to the Context which you want.

public class MyApplication extends Application { 

private Context context;

@Override
public onCreate() {
  super.onCreate();
  this.context = getApplicationContext() // Grab the Context you want.
}

public static Context getApplicationContext() { return this.context; }
}

This solution however requires that you specify the name of your subclass in your manifest.

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

You can then use this anywhere in your application like this in non-activity classes.

MyApplication.getContext();  // Do something with the context! :)

Leave a Comment