Using the Application Context

Access Application Context:

The application context is the central location for all top-level application functionality. You use the application context to access settings and resources shared across multiple activity instances.

You can retrieve the application context for the current process by using the getApplicationContext() method, like this:

Context context = getApplicationContext();

Because the Activity class is derived from the Context class, you can use the this object instead of retrieving the application context explicitly when you’re writing code inside your Activity class. After you have retrieved a valid application context, you can use it to access application-wide features and services.

The application context provides access to a number of top-level application features. Here are a few more things you can do with the application context:

  1. Launch Activity instances
  2. Retrieve assets packaged with the application
  3. Request a system-level service provider (for example, location service)
  4. Manage private application files, directories, and databases
  5. Inspect and enforce application permissions

The first item on this list—launching Activity instances—is perhaps the most common reason you will use the application context.

Access Application Resources:

You can retrieve application resources by using the getResources() method of the application context. The most straightforward way to retrieve a resource is by using its unique resource identifier, as defined in the automatically generated R.java class.

The following example retrieves a String instance from the application resources by its resource ID:

String greeting = getResources().getString(R.string.hello);

Before accessing any string resources you must have to declare it within the string.xml file in res folder.

Accessing Application Preferences:

You can retrieve shared application preferences by using the getSharedPreferences() method of the application context. You can use the SharedPreferences class to save simple application data, such as configuration settings. You can give each SharedPreferences object a unique name, enabling you to organize preference values into categories, or store preferences together in one large, unnamed set.

The following code creates a set of shared preferences called GamePrefs and saves a few such preferences:

SharedPreferences settings = getSharedPreferences(“GamePrefs”, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString(“UserName”, “Spunky”);
prefEditor.putBoolean(“HasCredits”, true);
prefEditor.commit();

To retrieve preference settings, you simply retrieve SharedPreferences and read the values back out:

SharedPreferences settings = getSharedPreferences(“GamePrefs”, MODE_PRIVATE);
String userName = settings.getString(“UserName”, “Chippy Jr. (Default)”);

Related posts