Here’s an example of using Explicit Intent in Jetpack Compose to navigate between two activities.
Step 1: Create Two Activities
MainActivity.kt
This is the starting activity that launches SecondActivity
.
package com.example.explicitintentexample
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MainScreen()
}
}
@Composable
fun MainScreen() {
Scaffold(
topBar = {
TopAppBar(title = { Text("Main Activity") })
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
Button(
onClick = {
val intent = Intent(this@MainActivity, SecondActivity::class.java).apply {
putExtra("message", "Hello from MainActivity!")
}
startActivity(intent)
},
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Go to Second Activity")
}
}
}
}
}
SecondActivity.kt
This activity receives the intent and displays the passed message.
package com.example.explicitintentexample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class SecondActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val message = intent.getStringExtra("message") ?: "No message received"
setContent {
SecondScreen(message)
}
}
@Composable
fun SecondScreen(message: String) {
Scaffold(
topBar = {
TopAppBar(title = { Text("Second Activity") })
}
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
Text(text = "Received Message:", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(8.dp))
Text(text = message, style = MaterialTheme.typography.bodyLarge)
}
}
}
}
Key Steps in the Code:
- MainActivity.kt:
- Created a button using Jetpack Compose.
- On button click, used an explicit intent to navigate to
SecondActivity
and passed data usingputExtra
.
- SecondActivity.kt:
- Retrieved the passed data using
intent.getStringExtra
. - Displayed the received message in the UI using Jetpack Compose.
Output:
- Main Activity: Displays a button labeled “Go to Second Activity.”
- Second Activity: Displays the message “Hello from MainActivity!” passed from the first activity.