Suppose, you create an android app which would like to access some user permission on runtime, let’s say notification. How can your app do that? How will your app knows, if the permission is already granted to your app or not? If not granted, how can it request the android system to provide a dialog to request permission from the user?
Well, that’s where context comes into play. A Context
will provide our app with all the information about this permission and other resources available for our app to utilize.
What is Context
A Context
refers to an environment or the state of the application. In other words, it is like a bridge that lets you interact with Android’s operating system and your app’s internal resources.
Role of Context
Context are used for many different things in our application. Few key roles that context plays in our applications are:
- Access resources such as Strings, colors, drawables, etc
- Access Files and cache directories
- Access Locally stored information
- Start activities, services and sending broadcasts.
- Access system services
- Check/request permissions
Types of Contexts
There are different types of context based on where and how they’re used:
1. Application Context
- Scope: Entire application lifecycle.
- Usage: For tasks that need a context tied to the app, not an individual activity (e.g., starting services, accessing resources).
- Accessed via:
getApplicationContext()
2. Activity Context
- Scope: Activity lifecycle.
- Usage: For UI-related operations like inflating layouts, launching dialogs.
- Accessed via:
this
(inside an Activity), orActivityName.this
3. Service Context
- Scope: Service lifecycle.
- Usage: Used within a Service for background operations.
- Accessed via:
this
(inside a Service)
4. BroadcastReceiver Context
- Scope: Limited to the duration of
onReceive()
. - Usage: Should not perform long-running tasks. Used to access system services briefly.
- Accessed via: The
Context
parameter inonReceive(Context context, Intent intent)
5. ContentProvider Context
- Scope: Used to access data across apps.
- Usage: For querying or managing shared data via
ContentResolver
. - Accessed via: The
Context
passed toonCreate()
of ContentProvider
Hence, this was all the basics , you need to know about contexts in android.