In Android development, Intents are a crucial mechanism for communication between different components of an app, such as Activities, Services, and Broadcast Receivers. They essentially represent a message that an app component sends to another component.
Types of Intents:
Explicit Intents:
Directly specify the target component by its class name.
Used for communication within your app.
Example:
// Java
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
2. Implicit Intents:
Define the action to be performed and the data to be used.
The system finds the appropriate component to handle the intent based on intent filters.
Used for system actions or invoking other apps.
Example:
// Java
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
Key Components of an Intent:
Action: Specifies the action to be performed (e.g., ACTION_VIEW, ACTION_SEND).
Data: Specifies the data to be used for the action (e.g., a URI, a file path).
Category: Specifies additional information about the intent (e.g., CATEGORY_DEFAULT, CATEGORY_BROWSABLE).
Extras: Additional data that can be passed with the intent (e.g., key-value pairs).
Common Use Cases:
Starting Activities: Launch new activities within your app or other apps.
Sending Data Between Activities: Pass data using extras.
Invoking System Services: Use implicit intents to trigger system actions like making calls, sending emails, or opening maps.
Receiving Broadcasts: Register Broadcast Receivers to listen for system-wide events or custom broadcasts.
Example: Starting a New Activity and Passing Data
Java
// In MainActivity:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("message", "Hello from MainActivity");
startActivity(intent);
// In SecondActivity:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
// Use the received message
Intent Filters:
Intent filters are used to declare which implicit intents an app component can handle. They are defined in the AndroidManifest.xml file.
XML
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT"
/>
<data android:scheme="http" android:host="www.example.com" />
</intent-filter>
</activity>