Android Intents with Kotlin
Tags: intents, kotlin, android, beginners
Published: 2020-03-01 11:43:10



We all have come across intents in different apps. Whether it is being able to share an image, start another activity or open a browser. Well, before an app can perform an action, it needs to know what that actions purpose is, or intent,  in order to carry out that action properly. So what exactly is an intent?

> An intent is a messaging object you can use to request an action from another app component.

 If you are an android Dev you might have used intents to launch an activity from an existing activity or to launch an app . There are number of tasks on apps that depend on the use of intents. In this blog we are going to cover implicit android intents using Kotlin. 

#### There are two types of Intents.
##### Implicit Intents – Allows you to have a separate app that performs an action such as “Send an email”
##### Explicit Intents – These are intents used to navigate between activities in your own app. This can be by launching another activity on the click of a button

With Intents in your app you can perform some actions such as, Call:telephone_receiver:, sending an email:email:, Browse, capture images :camera: or view the gallery. The idea of using intents is not having to build an individual activity or another app to perform an action, you can pass the intent and let another app perform the assigned action.  If you call the Implicit Intent, the android system searches for components that can be used to start the activity. This is done by comparing the contents of the intent with content present in the intent-filters declared in the <i>AndroidManifist.xml</i>.
 Intent Filters are expressions that are used to specify the type of components or actions that can be received by the application.


In this tutorial we shall build a simple Bio App where you shall be able to call, send an email and view the location with the use of implicit Intents.
 Unlike in Explicit intents where we declare the class name of the components to start, with implicit intents, we declare an action to be performed. Depending on the intent you want to create, the data might be an Uri(Uniform Resource Identifier).the intent might also not need data at all.
 
<b>Step 1.</b>  Crete a new Android Studio Project

<b>Step 2.</b>  Open the activity _main.xml and add the following code.

```
<?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">


    <com.androdocs.circleimagelibrary.CircleImageView
        android:id="@+id/circleImageView"
        android:layout_width="178dp"
        android:layout_height="178dp"
        android:src="@drawable/carol"
        app:border_color="#000000"
        app:border_width="2dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.145" />

    <Button
        android:id="@+id/bioview"
        android:layout_width="152dp"
        android:layout_height="53dp"
        android:background="@drawable/roundbutton"
        android:text="View My Bio"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/circleImageView"
        app:layout_constraintVertical_bias="0.085" />

</androidx.constraintlayout.widget.ConstraintLayout>
````

From the above xml code, I created an imageView and a button. I used a Circle image view and constraint layout. Well, it all depends on your preference when it comes to it. 
My drawable/roundbutton.xml


```
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/transparent"/>
   <stroke android:width="1dp" android:color="#ffff" />
    <corners android:radius="20dp"/>
</shape>
```


Intent filters declared in the AndroidManifest.xml

```
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
```

<b>Step 3</b>. Create another activity.  

<i>File>New>Activity>EmptyActivity</i>


<b>Step 4.</b>  Editing the activity_dets.xml




    <com.androdocs.circleimagelibrary.CircleImageView
        android:id="@+id/image"

        android:layout_width="178dp"
        android:layout_height="178dp"
        app:border_color="#000000"
        app:border_width="3dp"
        app:contentDescription="TODO"
        android:src="@drawable/carol"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.068"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.07" />

    <Button
        android:id="@+id/callme"
        android:layout_width="176dp"
        android:layout_height="43dp"
        android:layout_alignParentEnd="true"
        android:background="@drawable/roundbutton"
        android:backgroundTint="#DFA71CC4"
        android:paddingStart="20dp"
        android:paddingEnd="20dp"
        android:text="Call me"
        android:textAlignment="center"
        android:textSize="12sp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.885"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.079"
        tools:visibility="visible" />

    <Button
        android:id="@+id/emailme"
        android:layout_width="176dp"
        android:layout_height="43dp"
        android:layout_below="@+id/callme"
        android:layout_alignParentEnd="true"
        android:background="@drawable/roundbutton"
        android:backgroundTint="#DFA71CC4"
        android:text="Send me an email"
        android:textAlignment="center"
        android:textSize="12sp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.885"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/callme"
        app:layout_constraintVertical_bias="0.087"
        tools:visibility="visible" />

    <Button
        android:id="@+id/location"
        android:layout_width="176dp"
        android:layout_height="43dp"
        android:layout_below="@id/emailme"
        android:layout_alignParentEnd="true"
        android:background="@drawable/roundbutton"
        android:backgroundTint="#DFA71CC4"
        android:text="My Location"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.885"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.334" />

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="376dp"
        android:layout_height="291dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.813">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="@string/article"
            android:textAlignment="center"
            android:textSize="20sp" />
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

From the above code, we have created three buttons. One to allow a call to be made, another to send an email and another to view the location.
 First Lets add functionality to the button in the main activity to open our second activity. We shall use an explicit intents .



Step 4.  Adding functionality to the button in the main activity


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

        val viewbio = findViewById<Button>(R.id.bioview)
        viewbio.setOnClickListener {
            val intent = Intent(this, Dets::class.java)
            startActivity(intent)
        }


    }

On button click, we shall start our Dets activity. 

Step 5. Add functionality to the three buttons in DetsActivity. 




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



        val callme = findViewById<View>(R.id.callme)
        callme.setOnClickListener {
            val callIntent: Intent = Uri.parse("tel:+254712345678").let { number ->
                Intent(Intent.ACTION_DIAL, number)
            }
            startActivity(callIntent)


            Handler().postDelayed({
                Toast.makeText(
                    this,
                    "Please leave a message if I am not available",
                    Toast.LENGTH_LONG
                ).show()
            }, 4000)
        }


        val emailme = findViewById<View>(R.id.emailme)
        emailme.setOnClickListener {
            val intent = Intent(Intent.ACTION_SENDTO)
            intent.data = Uri.parse("mailto:youremail@gmail.com") // only email apps should handle this
            intent.putExtra(Intent.EXTRA_EMAIL, "")
            intent.putExtra(Intent.EXTRA_SUBJECT, "Feedback")
            startActivity(intent)

        }

             val locateme = findViewById<View>(R.id.location)
         locateme.setOnClickListener {
           // Build the intent
           val location =
               Uri.parse("geo:0,0?q=Home+Taita+Taveta+University&ftid=0x0:0xcc0f6fda95558a7e")
           val mapIntent = Intent(Intent.ACTION_VIEW, location)
 



From the above code we have three intents, callme, emailme and locateme. 
"callme" will initiate a phone call using the Uri data to specify the telephone number (“:+254712345678”). When your app invokes this intent by calling startActivity(), the Phone app initiates a call to the given phone number. The same applies to "locateme" whereas "emailme" does not require the use of an Uri.
locateme also requires the use an Uri

Other Intents you can try adding to your app; 

###### To open a browser

```
btn_browser.setOnClickListener(View.OnClickListener {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse("https://github.com/user/myportfolio")
    startActivity(intent)
})
```

###### To capture an image

```
btn_camera.setOnClickListener(View.OnClickListener {
    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    startActivity(intent)
})
```

PS: If you invoke an intent and there is no app on the device to handle it, your app will crush.

To verify there is an activity available that can respond to the intent, call queryIntentActivities() to get a list of activities capable of handling your Intent. If the returned List is not empty, you can safely use the intent.

Consider the one we used to verify if the app to handle the intent exists. 



```
// Verify it resolves
           val activities: List<ResolveInfo> = packageManager.queryIntentActivities(mapIntent, 0)
           val isIntentSafe: Boolean = activities.isNotEmpty()

// Start an activity if it's safe
           if (isIntentSafe) {
               startActivity(mapIntent)
           }
```


Get the full code from [here](https://github.com/carolinemusyoka/Bio)



The internet is resourceful. It does not come to an end from that. There is so much to learn about intents. From receiving and responding to intents from other apps, Verifying if there is an app to receive the intent and so much more. 

Keep learning and share what you learn!!! :sunglasses: