Article image Android Intents and Intent Filters

25. Android Intents and Intent Filters

Page 25 | Listen in audio

In the realm of Android development, Intents and Intent Filters play a crucial role as they enable communication between different components of an application, or even between different applications. Understanding Intents and Intent Filters is essential for any Android developer, especially when working with Kotlin, as it allows for seamless integration and interaction within the Android ecosystem.

Intents in Android can be thought of as messages that are sent between components such as activities, services, and broadcast receivers. They are used to request an action from another app component. Intents can be categorized into two types: explicit intents and implicit intents.

Explicit Intents

Explicit intents are used to start a specific component within your application. When you know the exact component you want to launch, you use an explicit intent. For instance, if you have two activities, MainActivity and DetailActivity, and you want to start DetailActivity from MainActivity, you would use an explicit intent. Here’s an example in Kotlin:

val intent = Intent(this, DetailActivity::class.java)
startActivity(intent)

In this example, the Intent constructor takes the current context and the target activity class as parameters, effectively telling the Android system precisely which activity to start.

Implicit Intents

Implicit intents, on the other hand, do not specify the target component. Instead, they declare a general action to perform, and it's up to the Android system to find the appropriate component to handle that action. This is where Intent Filters come into play. Intent Filters define the capabilities of a component and allow it to respond to implicit intents.

For example, if you want to open a web page, you can create an implicit intent with an action of Intent.ACTION_VIEW and a URI specifying the web page:

val webpage: Uri = Uri.parse("http://www.example.com")
val intent = Intent(Intent.ACTION_VIEW, webpage)
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

In this example, the Android system will look for an activity with an intent filter that matches the action ACTION_VIEW and the data type of a URI. If such an activity exists, it will be launched to handle the intent.

Intent Filters

Intent Filters are declared in the AndroidManifest.xml file and specify the types of intents a component can respond to. An intent filter can include the following elements:

  • Action: A string that specifies the general action to perform. Common actions include Intent.ACTION_VIEW, Intent.ACTION_EDIT, and Intent.ACTION_SEND.
  • Category: Provides additional information about the action. For example, Intent.CATEGORY_DEFAULT is often used in conjunction with other actions.
  • Data: Specifies the type of data the component can handle, such as a URI or MIME type.

Here’s an example of how to declare an intent filter in the manifest file:

<activity android:name=".DetailActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="http" />
    </intent-filter>
</activity>

In this example, DetailActivity can handle intents with the ACTION_VIEW action, the default category, and a URI with the "http" scheme.

Communicating Between Components

Intents are not just used for launching activities; they can also be used for starting services and broadcasting messages. When starting a service with an intent, you can pass data to the service through the intent’s extras. Similarly, broadcast intents can be used to send messages to multiple components that are listening for specific broadcasts.

Here’s an example of starting a service with an intent:

val intent = Intent(this, MyService::class.java)
intent.putExtra("EXTRA_DATA", "Some data")
startService(intent)

In this example, an intent is created to start MyService, and additional data is passed using putExtra(). The service can then retrieve this data when it starts.

Handling Results with Intents

Sometimes, you may need to start an activity and receive a result back. This is done using startActivityForResult() and onActivityResult(). In Kotlin, it’s common to use the new ActivityResultLauncher API, which is more modern and simplifies the process.

Here’s an example of using ActivityResultLauncher:

private lateinit var resultLauncher: ActivityResultLauncher<Intent>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data: Intent? = result.data
            // Handle the result
        }
    }

    val intent = Intent(this, SecondActivity::class.java)
    resultLauncher.launch(intent)
}

In this example, an ActivityResultLauncher is registered to handle the result from SecondActivity. When the result is received, it can be processed in the lambda function.

Conclusion

Intents and Intent Filters are fundamental concepts in Android development, enabling components to communicate and interact with each other. Whether you’re launching activities, starting services, or broadcasting messages, understanding how to use intents effectively is key to building robust Android applications. With Kotlin’s concise syntax and powerful features, working with intents becomes even more intuitive and efficient, allowing you to focus on creating seamless user experiences.

Now answer the exercise about the content:

What are the two types of intents in Android development?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Data Persistence in Android

Next page of the Free Ebook:

26Data Persistence in Android

8 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text