Menu

Android Get Application Context

If we code inside an Activity and we need the application context we can use getApplicationContext().

Inside an Activity we can use getApplicationContext() if we need the application context. But what if we are not inside an Activity and we need that? I will explain how you can get the context of the application outside an Activity with simple coding.

First, you have to create a new class “ApplicationContextProvider” extends Application which will provide the context wherever in the application.


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 open the AndroidManifest.xaml and declare “ApplicationContextProvider” class 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

android manifest

android manifest



Source : http://www.myandroidsolutions.com/2013/04/27/android-get-application-context/

Cheers and Happy Coding Guys :)

Comments (0)

Leave a comment

Your email address will not be published. Required fields are marked *