LiveData and Data Binding
# Chapter 18: Understanding Context and Intent Filters
1. Introduction
Two of the most frequently used, yet often misunderstood, concepts in Android development are Context and Intents. While we touched on explicit Intents earlier for navigating between Activities, this chapter dives deeper into the Android operating system's communication systems: Implicit Intents, Intent Filters, and the all-important Context.2. Learning Objectives
By the end of this chapter, you will be able to:-
Understand what
Contextis and why almost every Android API requires it.
- Differentiate between Application Context and Activity Context to avoid memory leaks.
- Use Implicit Intents to open web pages, dial numbers, and share text.
-
Configure
Intent Filtersin the Manifest so your app can respond to system-wide actions.
3. Core Concepts & Implementation
What is Context?
Context is exactly what it sounds like—it provides the "context" of the current state of the application or object. It is an abstract class that provides access to app-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting, and receiving intents.
Types of Context:
-
1.
Activity Context (
this): Tied to the lifecycle of an Activity. Use this for UI-related operations (like showing a Dialog or Toast). It is destroyed when the Activity is destroyed.
-
2.
Application Context (
applicationContext): Tied to the lifecycle of the entire application. Use this for things that need to live longer than a single Activity (like a database instance or a network client).
*Crucial Rule:* Never pass an Activity Context to an object that outlives the Activity (like a background thread or a singleton class), or you will cause a Memory Leak.
Implicit Intents
Earlier, we used *Explicit Intents* to say "Start *MySecondActivity*". An Implicit Intent doesn't specify the exact component to start. Instead, it declares a *general action* to perform, allowing the Android OS to find any app on the device that can handle that action.Example 1: Opening a Web Page
*If multiple browsers are installed, Android will ask the user which one to use.*
Example 2: Dialing a Phone Number
Example 3: Sharing Text
Intent Filters
If Implicit Intents are how you *ask* the system to do something, Intent Filters are how your app tells the system "I can do that!"You define Intent Filters in your AndroidManifest.xml inside an <activity> tag.
Example: Making your app a Web Browser If you want your app to open URLs from other apps, you add an intent filter:
When a user clicks a link in an email, the Android OS sees that your app can handle ACTIONVIEW for http schemes, and offers your app as an option!
4. Best Practices
-
Use
resolveActivity: Before callingstartActivity()with an implicit intent, it's good practice to check if there is actually an app on the device that can handle it.
kotlin
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
// Show an error toast
}
`
-
Context Selection: Default to using Activity context for UI work. Only use
applicationContext when you explicitly need a context that survives the Activity.
5. Exercises
-
1.
Create a button that opens Google Maps to a specific latitude and longitude using an Implicit Intent (
geo:lat,lng).
-
2.
Add an intent filter to your
MainActivity so it can handle "Share" actions (ACTIONSEND of type text/plain). In onCreate, check intent.action and print the shared text to a TextView.
6. Coding Challenge
The Universal Hub App
Create an application with three buttons:
-
1.
"Email Us" -> Opens an email client with a pre-filled "To" address and Subject. (Action:
ACTIONSENDTO, Data: mailto:test@example.com).
-
2.
"Call Us" -> Opens the dialer.
-
3.
"Share App" -> Shares a promotional string to WhatsApp, Twitter, etc.
7. Multiple Choice Questions (MCQs)
-
1.
Which context should be passed to a Singleton class that manages a local database?
-
a) Activity Context (
this)
-
b) Service Context
-
c) Application Context (
applicationContext)
-
d) Fragment Context
-
2.
What type of Intent specifies an action like
ACTIONVIEW rather than a specific class?
-
a) Explicit Intent
-
b) Implicit Intent
-
c) Pending Intent
-
d) Broadcast Intent
-
3.
Where do you declare an Intent Filter to tell the OS what your activity can handle?
-
a)
build.gradle
-
b)
MainActivity.kt
-
c)
AndroidManifest.xml
-
d)
strings.xml
-
4.
What happens if you call
startActivity(implicitIntent) and no app on the device can handle the action?
-
a) The OS downloads a compatible app.
-
b) Nothing happens.
-
c) The app crashes with an
ActivityNotFoundException.
-
d) The intent is queued for later.
8. Interview Questions
-
1.
What is a Memory Leak in Android, and how does Context cause it?
*Answer*: A memory leak occurs when objects are no longer needed but cannot be garbage collected because something is still holding a reference to them. If you pass an Activity context to a long-running background thread, the Activity cannot be destroyed when the user leaves it, leaking a massive amount of memory (the whole UI).
-
2.
Explain the difference between Explicit and Implicit Intents.
*Answer*: Explicit intents specify the exact class name of the component to start (e.g., Intent(this, SecondActivity::class.java)), used internally within an app. Implicit intents specify an action (e.g., ACTION_VIEW), allowing the system to find any component from any app that can handle that action.
-
3.
What is the purpose of
Intent.createChooser()`?
*Answer*: It forces the Android OS to show a dialog listing all apps that can handle an implicit intent, rather than silently using the user's default app. It is heavily used for "Share" actions.