In Android development, navigating between activities is a fundamental task that allows users to move from one screen to another. In Kotlin-based XML development, this navigation is primarily handled using Intents. An Intent is a messaging object you can use to request an action from another app component. Although this blog post concentrates on navigation using Activities, Intents also are used for services and broadcast receivers.
Understanding Intents
An Intent is a powerful tool for inter-component communication. They are primarily used for:
- Starting an activity
- Starting a service
- Delivering a broadcast
For this guide, we’ll focus on starting activities, which is crucial for app navigation.
Types of Intents
There are two types of Intents:
- Explicit Intents: Specify the component to start by class name. They are typically used within the same application because the target component is precisely known.
- Implicit Intents: Declare the general action to perform, allowing the system to find a component from another application that can handle the intent. This type doesn’t specify what the component is for security concerns and tight coupling concerns.
Prerequisites
Before we dive into the code, ensure that you have:
- Android Studio installed
- Basic knowledge of Kotlin and Android development
- Familiarity with XML layouts
Step-by-Step Guide
Let’s walk through creating navigation between two activities using both explicit and implicit intents.
Step 1: Project Setup
Create a new Android project in Android Studio using Kotlin. Let’s name it ‘IntentNavigation’. Configure the project settings as desired.
Step 2: Create Activities
First, you need two activities: MainActivity (the main screen) and SecondActivity (the screen to navigate to). The MainActivity will start with, as that is default in the AndroidManifest.xml configuration. By right-clicking on app -> java -> your_package_name in the Project Navigator window, navigate to New -> Activity -> Empty Activity to add a new activity and call it SecondActivity. Then follow the steps in that creation Wizard.
Step 3: Update Layout Files
Update activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/explicitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity (Explicit)"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="32dp" />
<Button
android:id="@+id/implicitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open URL (Implicit)"
app:layout_constraintTop_toBottomOf="@id/explicitButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Next, update activity_second.xml. This is a destination activity.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the Second Activity!"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Implement Explicit Intent
In MainActivity.kt, add an OnClickListener to navigate to SecondActivity using an explicit intent. You will also add code to handle the Implicit intent.
package com.example.intentnavigation
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val explicitButton: Button = findViewById(R.id.explicitButton)
val implicitButton: Button = findViewById(R.id.implicitButton)
explicitButton.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
implicitButton.setOnClickListener {
val url = "https://www.example.com"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
}
}
Here’s a summary of this block of code.
- The example sets up an
explicitButtonwith anOnClickListener, which creates an explicit intent to navigate from the current activity (MainActivity) toSecondActivitywhen the button is pressed. ThisIntentspecifies the target component by class name. ThestartActivity(intent)call launchesSecondActivity. - An
implicitButtonis set up similarly. Thisintentaction opens a URL ("https://www.example.com") in a web browser or another suitable app. TheIntentusesIntent.ACTION_VIEWto signify the action of viewing a URI and passes the URI to be viewed (parsed from the URL string) to the Intent. The operating system decides the app that fulfills this request.
Step 5: Modify AndroidManifest.xml
While explicit intents typically do not require changes to AndroidManifest.xml for basic use cases (navigation within the same app), let’s review it to ensure SecondActivity is properly declared.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentnavigation">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.IntentNavigation">
<activity
android:name=".SecondActivity"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
Step 6: Run Your App
Run your Android application on an emulator or physical device. Pressing the ‘Go to Second Activity (Explicit)’ button should navigate you to the Second Activity, and pressing ‘Open URL (Implicit)’ button should open your default web browser. This is implicit because this action does not happen within your app. Instead, another application takes care of this.
Passing Data Between Activities
You can also pass data between activities using Intents. This allows more contextualization for other Activities when transitioning between them.
Sending Data from MainActivity to SecondActivity:
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "Hello from MainActivity!")
startActivity(intent)
Receiving Data in SecondActivity:
val message = intent.getStringExtra("key")
val textView: TextView = findViewById(R.id.textView)
textView.text = message
Be mindful about using correct data keys and validating their values since the absence of that validation can lead to bugs.
Conclusion
Navigating between activities in Kotlin-based Android development using Intents is straightforward. Explicit Intents provide precise navigation within your application, while Implicit Intents allow you to leverage other applications for actions such as opening web pages. You’ve seen and hopefully implemented everything, step by step, from project setup, button implementations, and navigation between activities using different types of intents. Using these principles provides the means to allow your applications to fully come to life in providing a unique experience for the end users.