Step 4: Mastering Intents in Android - Navigation and Data Sharing

Working with Intents: Navigation and Data Sharing in Android

Welcome to Step 4 of your Android development journey! Now that you understand Activities, Layouts, and Views, it’s time to explore how they interact.

Photo by Susan Q Yin on Unsplash


In this guide, we’ll delve into Intents — the mechanism that powers navigation and data sharing between components in Android apps. By the end, you’ll be able to navigate between screens and use both explicit and implicit Intents to make your app more dynamic.


What Are Intents?

An Intent is a messaging object that allows communication between Android components such as Activities, Services, and Broadcast Receivers.

Key Purposes of Intents in Android:

  • Launching Activities: Intents are primarily used to start new activities or navigate between screens in an app.
  • Starting Services: Intents can be used to start or bind to services, allowing background tasks such as data fetching or computation to occur.
  • Broadcasting Messages: Intents can be sent as broadcast messages, which can be received by other apps or system components, like notifications or system events.
  • Inter-App Communication: Through implicit intents, apps can request other apps to handle tasks such as opening a URL or sending a message.

    There are two main types of Intents:

    1. Explicit Intents: Directly specify the target component.
    2. Implicit Intents: Specify an action to be performed without identifying the target component explicitly.

    Using Explicit Intents

    Explicit Intents specify the exact component (Activity, Service, or BroadcastReceiver) that should handle the intent. You specify the class name of the target component explicitly.

    Use Cases:

    • Navigating between activities (e.g., opening a new screen from a button click).
    • Starting a service or sending data to a service.
    • Sending data to a broadcast receiver.

    Example: Navigating Between Two Activities

    1. Create Two Activities:
      • MainActivity.kt
      • SecondActivity.kt

    2. Design the Layouts:
      • activity_main.xml
      <Button
          android:id="@+id/navigateButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Go to Second Activity" />
      • activity_second.xml
      <TextView
          android:id="@+id/textView"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Welcome to the Second Activity!" />

    3. Add Navigation Logic in MainActivity.kt:
    4. val navigateButton: Button = findViewById(R.id.navigateButton)
      
      navigateButton.setOnClickListener {
          val intent = Intent(this, SecondActivity::class.java)
          startActivity(intent)
      }

    With this setup, clicking the button navigates to the second Activity.

    Exercise:

    • Add a button in SecondActivity to navigate back to MainActivity.
    • Pass a simple message from MainActivity to SecondActivity and display it in a TextView.

    Using Implicit Intents

    Implicit Intents do not specify a specific component. Instead, they declare a general action to be performed. The Android system then determines the best component to handle the intent based on the provided action, data, and categories.

    Use Cases:

    • Opening a web page using the browser.
    • Sending an email.
    • Viewing or editing a contact.
    • Sharing data between apps.

    How an implicit intent is delivered through the system to start another activity


    Example: Opening a Webpage

    val openWebButton: Button = findViewById(R.id.openWebButton)
    openWebButton.setOnClickListener {
        val webpage: Uri = Uri.parse("https://www.example.com")
        val intent = Intent(Intent.ACTION_VIEW, webpage)
        startActivity(intent)
    }

    Here, Intent.ACTION_VIEW signals that you want to view the webpage specified by the Uri.

    Example: Sharing Text

    val shareButton: Button = findViewById(R.id.shareButton)
    shareButton.setOnClickListener {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_TEXT, "Check out this cool app!")
        startActivity(Intent.createChooser(intent, "Share via"))
    }

    Exercise:

    • Create a button to send an email using Intent.ACTION_SENDTO.
    • Use an implicit Intent to open the dialer with a predefined phone number.

    Passing Data Between Activities

    Intents can also carry data using key-value pairs known as "extras."

    Example: Sending Data to Another Activity

    1. Send Data from MainActivity.kt:

      val intent = Intent(this, SecondActivity::class.java)
      intent.putExtra("USER_NAME", "John Doe")
      startActivity(intent)
    2. Receive Data in SecondActivity.kt:

      val userName = intent.getStringExtra("USER_NAME")
      val textView: TextView = findViewById(R.id.textView)
      textView.text = "Welcome, $userName!

    Exercise:

    • Pass multiple pieces of data (e.g., username and age) and display them in the second Activity.


    Real-World Use Case: Login and Profile Navigation

    Let’s create a simple flow where a user logs in and navigates to their profile screen.

    Step 1: Create Login and Profile Activities

    • LoginActivity: Includes EditText fields for username and password, and a login button.
    • ProfileActivity: Displays a welcome message with the username.

    Step 2: Design Layouts

    • activity_login.xml:
      <EditText
          android:id="@+id/usernameInput"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="Enter Username" />
      
      <Button
          android:id="@+id/loginButton"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Login" />
    • activity_profile.xml:
      <TextView
          android:id="@+id/welcomeText"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="" />

    Step 3: Implement Logic

    • LoginActivity.kt:
      val loginButton: Button = findViewById(R.id.loginButton)
      loginButton.setOnClickListener {
          val username = findViewById<EditText>(R.id.usernameInput).text.toString()
          val intent = Intent(this, ProfileActivity::class.java)
          intent.putExtra("USERNAME", username)
          startActivity(intent)
      }
    • ProfileActivity.kt:
      val username = intent.getStringExtra("USERNAME")
      val welcomeText: TextView = findViewById(R.id.welcomeText)
      welcomeText.text = "Welcome, $username!"

    Summary

    In this step, you learned:

    1. Explicit Intents: Navigate between specific components in your app.
    2. Implicit Intents: Perform actions like opening a webpage or sharing data.
    3. Data Sharing: Pass information between Activities using Intents.

    What’s Next?

    In the next step, we’ll dive into Fragments — a powerful way to create dynamic and reusable UIs in your Android apps. Stay tuned and don’t forget to subscribe for updates!


    Stay Tuned!Don’t forget to subscribe and follow for the next steps in this series. Got questions? Drop them in the comments below—I’m here to help!

    Let’s get coding and bring your app ideas to life!

    Pragnesh Ghoda

    A forward-thinking developer offering more than 8 years of experience building, integrating, and supporting android applications for mobile and tablet devices on the Android platform. Talks about #kotlin and #android

    Post a Comment

    Please let us know about any concerns or query.

    Previous Post Next Post

    Contact Form