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
- Explicit Intent: Directly specifies the target component (e.g., a specific activity or service).
- Used within the same application.
- Example: Launching a specific activity.
- 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
- Action: Defines the general action to perform (e.g.,
ACTION_VIEW
,ACTION_SEND
). - Data: URI or MIME type specifying the data to act upon.
- Category: Provides additional information about the component to be invoked.
- Extras: Key-value pairs carrying additional data.
- 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:
FLAG_ACTIVITY_NEW_TASK
: Start a new task for the activity.FLAG_ACTIVITY_CLEAR_TOP
: Clear all activities above the target activity in the stack.FLAG_ACTIVITY_SINGLE_TOP
: Avoid launching a new instance if the activity is already on top.
Returning Results with Intents
- Launching Activity for Result:
val intent = Intent(this, SecondActivity::class.java)
startActivityForResult(intent, REQUEST_CODE)
- Returning Data from Target Activity:
val intent = Intent()
intent.putExtra("result", "Data from SecondActivity")
setResult(RESULT_OK, intent)
finish()
- 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
- Security: Avoid exposing sensitive data with implicit intents.
- Validation: Validate received data in the target component.
- Optimization: Use explicit intents where possible for better performance and security.