Intents and Intent Filters in Android
What is an Intent?
An Intent in Android is a messaging object used to request actions from other components like activities, services, and broadcast receivers. It can either be:
IntentFilter and Its Purpose
An IntentFilter specifies the types of intents a component can handle. It is crucial for allowing your app to respond to external requests, such as sharing content.
Examples:
1. Open an Activity Within Your App
Explicit Intent:
To open another activity within your app, you use an explicit Intent, which needs two parameters: the context (usually this or applicationContext) and the target activity.
val intent = Intent(this, TargetActivity::class.java)
startActivity(intent)
This code creates an explicit intent, telling Android to start TargetActivity. Once executed, the user sees the new screen (activity).
2. Passing Data with Intent
When you want to pass data to another activity, you can use putExtra to add key-value pairs to the intent.
val intent = Intent(this, TargetActivity::class.java).apply {
putExtra("KEY_NAME", "Hello!")
}
startActivity(intent)
This intent carries a string extra, which can be retrieved in TargetActivity using getIntent().getStringExtra("KEY_NAME").
3. Opening External Apps (Explicit Intent)
When you want to open a specific app like YouTube, you use an explicit intent that targets the app’s package with a specific ACTION like ACTION_MAIN which opens its MainActivity.
val youtubeIntent = Intent(Intent.ACTION_MAIN).apply {
setPackage("com.google.android.youtube")
}
if (youtubeIntent.resolveActivity(packageManager) != null)
startActivity(youtubeIntent)
This code checks if YouTube is installed and opens it if available. If the app is not installed, nothing happens unless you handle this case (e.g., prompting the user to download the app).
4. Implicit Intent for Sharing Files
Implicit intents allow you to interact with other apps without targeting a specific app. For sharing content, you use Intent.ACTION_SEND.
领英推荐
val shareIntent = Intent(Intent.ACTION_SEND).apply {
type = "image/*"
putExtra(Intent.EXTRA_STREAM, imageUri)
}
startActivity(Intent.createChooser(shareIntent, "Share Image"))
This code creates an intent for sending an image. A chooser dialog is displayed, showing all apps capable of receiving an image. The user selects an app, and the image is shared.
Receiving Shared Data in Your App
To make your app appear in the share options for images or videos, declare an IntentFilter:
Intent filters allow apps to specify which intents they can handle, enabling Android to route the right action to the appropriate app or component. They play a crucial role in enabling implicit intents to work by defining the types of actions, categories, and data that an app can respond to. With intent filters, your app can interact dynamically with other apps, offering greater flexibility, such as sharing data or handling incoming content from external sources.
<activity android:name=".ShareReceiverActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
</activity>
The <category> element in an IntentFilter specifies the role or capabilities of the component that should handle the intent. For example, "android.intent.category.DEFAULT" is required for activities launched through implicit intents.
Handling Single and Multiple Files
If another app shares data (like an image or file) with your app, you can handle it using Intent.ACTION_SEND and ACTION_SEND_MULTIPLE.
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent?) {
when (intent?.action) {
Intent.ACTION_SEND -> {
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
uri?.let { // Handle single image/video }
}
Intent.ACTION_SEND_MULTIPLE -> {
val uris = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
uris?.forEach { // Handle multiple images/videos }
}
}
}
This method handles the shared data (e.g., an image). If the shared content is an image or video or even a list of them, the URI is extracted and processed in your app.
PendingIntent for Deferred Actions
PendingIntent is useful for delegating an action to be performed in the future by another app or service such as in notifications or background tasks.
val intent = Intent(this, NotificationReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
This PendingIntent can be triggered later (e.g., when the user taps a notification). It allows your app to schedule tasks that will execute in the future, even if your app is no longer running.
Starting in Android 11, use <queries> in your AndroidManifest.xml to declare to check if an app (like YouTube) is installed.
<queries>
<package android:name="com.google.android.youtube" />
</queries>
This tag allows your app to query the package manager for YouTube’s presence. You can then use this information to decide if you can open the app or handle the situation when it's not installed.
Conclusion
These intents allow your app to interact seamlessly with other components, whether within the app or across apps, providing a flexible and powerful way to handle different actions and user interactions in Android.