Home / Programming / Android / Android Intents : All you need to know + Example

Android Intents : All you need to know + Example

What are Android Intents?

Android Intent is a simple message object which is used to communicate from one activity to another.

Intents are like envelopes, each one includes which component (activity) you want to deliver to and there’s room for small amount of data to be delivered packaged as extras which are primitive topples. That can be read by the app component that ultimately receives and opens the intent.

Instead of having activities call each other directly, android facilitates communication using messaging objects Called intents.

Intents let an app request that an action take place, that can be anything from starting a new activity to picking or displaying photo from a phone gallery or making a phone call.

An Android Intent can be used to perform following 3 tasks :
1. Open another Activity or Service from the current Activity
2. Pass data between Activities and Services
3. Delegate responsibility to another application. For example, you  can use Intents to open the browser application to display a URL.

Types of Intent

1- Explicit Intents

Explicit Android Intent is the Intent in which you explicitly define the component that needs to be called by Android System. When you open an activity from another activity in the same Android app, you use Explicit Intents.

val destinationClass = ChildActivity::class.java
val context = this
val intent = Intent(context, destinationClass)
startActivity(intent)

2- Implicit Intents

Implicit Android Intents is the intent where instead of defining the exact components, you define the action you want to perform. The decision to handle this action is left to the operating system. The OS decides which component is best to run for implicit intents.

Whenever you delegate responsibility to another application from your application, you use Implicit Intents. Below code tries to demonstrate how to use implicit intent to share text with another app.

val shareBody = "Here is the share content body"
val sharingImplicitIntent = Intent(Intent.ACTION_SEND)
sharingImplicitIntent.setType("text/plain")
sharingImplicitIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here")
sharingImplicitIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingImplicitIntent, "Title of Share Dialog"))

This is typically used when you want to share the data from one application to another. Sharing data over email, sms, social network etc. is a classic example of this category.

Data is typically expressed as a Uri which can represent an image in the gallery or person in the contacts database.

The amount of application that can be done using implicit intents are many. Some of the examples are as follows:

  • Call
  • Dialpad
  • Contact
  • Browser
  • Call Log
  • Gallery
  • Camera etc

Basic Example

Grab source code on GitHub

1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="24dp"
        android:textSize="22sp"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Any text here will be carried to a new Activity" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="Launch Explicit Intent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText1" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="32dp"
        android:textSize="22sp"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        tools:text="Any text here can be dealth with by any component" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="Launch Implicit Intent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

</android.support.constraint.ConstraintLayout>

2. MainActivity.kt

class MainActivity : AppCompatActivity() {
    companion object {
        val INTENT_KEY = "intent_extra_key"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val explicitIntentEditText = findViewById<TextView>(R.id.editText1)
        val explicitIntentButton = findViewById<Button>(R.id.button1)
        explicitIntentButton.setOnClickListener { v ->
            val destinationClass = ChildActivity::class.java
            val context = this
            val intent = Intent(context, destinationClass)
            val stringFromExplicitIntentEditTextView = explicitIntentEditText.text.toString()
            if (stringFromExplicitIntentEditTextView.trim().length > 1) {
                intent.putExtra(INTENT_KEY, stringFromExplicitIntentEditTextView)
                startActivity(intent)
            } else
                showToastMsg("Input some text to launch an Explicit Intent")
        }

        val implicitIntentEditText = findViewById<TextView>(R.id.editText2)
        val implicitIntentButton = findViewById<Button>(R.id.button2)
        implicitIntentButton.setOnClickListener { v ->
                val textToShare = stringFromImplicitIntentEditTextView
                val mimeType = "text/plain"
                val subject = "Subject of Content to Share" // you would need a "subject" if a user selects an email app to fulfill the intent
                val context = this
                ShareCompat.IntentBuilder.from(context)
                        .setType(mimeType)
                        .setSubject(subject)
                        .setText(textToShare)
                        .startChooser()
            } else
                showToastMsg("Input some text to launch an Implicit Intent")
        }

    }

    private fun showToastMsg(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}

3. activity_child.xml

<android.support.constraint.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=".ChildActivity">

    <TextView
        android:id="@+id/child_activity_text_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:textSize="30sp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Text sent from Explicit Intent" />
</android.support.constraint.ConstraintLayout>

4. ChildActivity.kt

class ChildActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_child)
        val textView = findViewById<TextView>(R.id.child_activity_text_view)

        val intent4rmMainActivity = intent
        if (intent4rmMainActivity != null){
            val string4rmExplicitIntent = intent4rmMainActivity.getStringExtra(INTENT_KEY)
            textView.setText(string4rmExplicitIntent)
        }
    }
}

 

About Edge Developer

Hello there, my name is Opeyemi Olorunleke. I am a Software Developer (majorly Android, GitHub Profile), Digital Marketer, Udemy Instructor, Technical Writer, Blogger & Webmaster.

Check Also

Android Admob Consent SDK : All you need to know + Example

First of all, let me address Google’s complacency to help app developers implement the GDPR …

Leave a Reply

Your email address will not be published. Required fields are marked *