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:
And that's all. You can get now the application context wherever you need it by simply calling
Continue reading →
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();
