Call Intent | Android Studio | Kotlin

Call Intent:

We will use intent to open the dialer with the phone number the user entered. In this example, we will input a phone number using an input field i.e. EditText, and open that phone number in the dialer screen by clicking the button.

>>Check For Java

Code Snippet:

val intent = Intent(Intent.ACTION_VIEW, Uri.parse("tel:${Uri.encode(phone)}"))
startActivity(intent)

Full Example:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context=".MainActivity1">

    <!--EditText: Input Phone Number-->
    <EditText
        android:id="@+id/phoneEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Phone Number"
        android:inputType="phone" />

    <!--MaterialButton: Click to open call intent-->
    <com.google.android.material.button.MaterialButton
        android:id="@+id/callBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="60dp"
        android:text="Call"
        app:cornerRadius="8dp" />

</LinearLayout>

MainActivity.java
package com.technifysoft.myapplication

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton

class MainActivity : AppCompatActivity() {

    private lateinit var phoneEt: EditText
    private lateinit var callBtn: MaterialButton

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

        phoneEt = findViewById(R.id.phoneEt)
        callBtn = findViewById(R.id.callBtn)

        callBtn.setOnClickListener {
            openCallIntent()
        }

    }

    private fun openCallIntent() {
        //input phone number
        val phone = phoneEt.text.toString().trim()

        //open call/dialer intent
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("tel:${Uri.encode(phone)}"))
        startActivity(intent)
    }

}

Output:

Call Intent | Android Studio | KotlinCall Intent | Android Studio | Kotlin


Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)