Using the Application Context Android

The application Context is the central location for all top-level application functionality. The Context class can be used to manage application-specific configuration details as well as application-wide operations and data. Use the application Context to access settings and resources shared across multiple Activity instances.

Retrieving the Application Context

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

Using the Application Context

After you have retrieved a valid application Context, it can be used to access application wide features and services.

Retrieving Application Resources

You can retrieve application resources using the getResources() method of the application Context. The most straightforward way to retrieve a resource is by using its resource identifier, a unique number automatically generated within the class. The following example retrieves a String instance from the application resources by its resource ID:

We talk more about application resources in Chapter “Managing Application Resources.”

Accessing Application Preferences

You can retrieve shared application preferences using the getSharedPreferences() method of the application Context.The SharedPreferences class can be used to save simple application data, such as configuration settings. We talk more about application preferences in Chapter “Using Android Data and Storage APIs.”

Accessing Other Application Functionality Using Context

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

  • Launch Activity instances
  • Retrieve assets packaged with the application
  • Request a system service (for example, location service)
  • Manage private application files, directories, and databases
  • Inspect and enforce application permissions

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

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Android Topics