Wednesday 25 September 2013

Android Get Application Context

When we are inside an activity, and we need an application context we can use
getApplicationContext() method. But what if we are not inside an activity and we need an application context? Well, I'll 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, 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


1
ApplicationContextProvider.getContext();


No comments:

Post a Comment