Tue. Jan 14th, 2025

Intents in Android

An Intent is a messaging object in Android used to request actions from another app component (e.g., activity, service, broadcast receiver). It facilitates communication between components and is a key mechanism for enabling user navigation and inter-app communication.


Types of Intents

  1. Explicit Intent: Directly specifies the target component (e.g., a specific activity or service).
  • Used within the same application.
  • Example: Launching a specific activity.
  1. Implicit Intent: Does not specify the target component. The system determines the best component to handle the intent based on intent filters.
  • Used for actions like opening a webpage, sharing content, or making a call.

Key Components of an Intent

  1. Action: Defines the general action to perform (e.g., ACTION_VIEW, ACTION_SEND).
  2. Data: URI or MIME type specifying the data to act upon.
  3. Category: Provides additional information about the component to be invoked.
  4. Extras: Key-value pairs carrying additional data.
  5. Flags: Instructions about how the activity should be launched (e.g., FLAG_ACTIVITY_NEW_TASK).

Explicit Intent Example

Launching Another Activity:

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("message", "Hello from MainActivity")
startActivity(intent)

Receiving Data in the Target Activity:

val message = intent.getStringExtra("message")
Log.d("SecondActivity", "Message received: $message")

Implicit Intent Example

Opening a Web Page:

val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"))
startActivity(intent)

Making a Phone Call:

val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:+1234567890"))
startActivity(intent)

Sharing Content:

val intent = Intent(Intent.ACTION_SEND).apply {
    type = "text/plain"
    putExtra(Intent.EXTRA_TEXT, "Check out this awesome app!")
}
startActivity(Intent.createChooser(intent, "Share via"))

Intent Filters

An Intent Filter allows an activity, service, or broadcast receiver to declare which implicit intents it can handle.

Example: Manifest Declaration

<activity android:name=".MyActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" android:host="www.example.com" />
    </intent-filter>
</activity>

Intent Flags

Flags modify how intents behave when launching activities. Common flags include:

  1. FLAG_ACTIVITY_NEW_TASK: Start a new task for the activity.
  2. FLAG_ACTIVITY_CLEAR_TOP: Clear all activities above the target activity in the stack.
  3. FLAG_ACTIVITY_SINGLE_TOP: Avoid launching a new instance if the activity is already on top.

Returning Results with Intents

  1. Launching Activity for Result:
   val intent = Intent(this, SecondActivity::class.java)
   startActivityForResult(intent, REQUEST_CODE)
  1. Returning Data from Target Activity:
   val intent = Intent()
   intent.putExtra("result", "Data from SecondActivity")
   setResult(RESULT_OK, intent)
   finish()
  1. Receiving Results in the Caller Activity:
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       super.onActivityResult(requestCode, resultCode, data)
       if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
           val result = data?.getStringExtra("result")
           Log.d("MainActivity", "Result received: $result")
       }
   }

Broadcast Intents

Broadcast intents are sent to broadcast receivers to notify multiple components of a system-wide event.

Sending a Broadcast:

val intent = Intent("com.example.CUSTOM_ACTION")
intent.putExtra("key", "value")
sendBroadcast(intent)

Receiving a Broadcast:

class MyReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val value = intent.getStringExtra("key")
        Log.d("MyReceiver", "Received: $value")
    }
}

Registering the Receiver:

In AndroidManifest.xml:

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="com.example.CUSTOM_ACTION" />
    </intent-filter>
</receiver>

Best Practices

  1. Security: Avoid exposing sensitive data with implicit intents.
  2. Validation: Validate received data in the target component.
  3. Optimization: Use explicit intents where possible for better performance and security.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *