Get application context from non activity singleton class

Update: 06-Mar-18

Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself.

public class MyApplication extends Application {

    private static MyApplication mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static MyApplication getContext() {
        return mContext;
    }
}

Previous Answer

You can get the the application context like this:

public class MyApplication extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

Then, you can call the application context from the method MyApplication.getContext()

Don’t forget to declare the application in your manifest file:

<application
    android:name=".MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

Leave a Comment