Android Get Application Context

When we are inside an Activity, and we need the application context we can use

getApplicationContext()

 method. But what if we are not inside an Activity and we need the application context? Well, I will explain in this tutorial how you can get the context of the application outside an Activity.

You have to create a new class called “ApplicationContextProvider” which will provide the context wherever in the application. The code looks like this:

import android.app.Application;
import android.content.Context;

public class ApplicationContextProvider extends Application {

    /**
     * Keeps a reference of the application context
     */
    private static Context sContext;

    @Override
    public void onCreate() {
        super.onCreate();

        sContext = getApplicationContext();

    }

    /**
     * Returns the application context
     *
     * @return application context
     */
    public static Context getContext() {
        return sContext;
    }

}

Now you have to declare this class in the AndroidManifest.xml in the application tag:

<application android:name=".ApplicationContextProvider" 
             android:label="@string/app_name">

And that’s all. You can get now the application context wherever you need it by simply calling

ApplicationContextProvider.getContext();

NOTE: The Application Context can be used to load resources, send broadcast messages and do other system like stuff and NOT on instantiating Views !

 

Sponsored message:


Programming Tip : Worried about your incomplete/pending software project? Now you can remotely catch up with your pending/missing programming work by accessing your programming tools such as emulators/IDE`s on high performance citrix xendesktop from CloudDesktopOnline with cheapest xendesktop cost. Now you can add complete MS Office suite to the same xendesktop by visiting O365CloudExperts.com powered by Apps4Rent.

Menu