Make A Call from Android App In Kotlin Version

In this tutorial, you will learn how to implement a feature in an Android app using Kotlin that enables users to make phone calls from a specified number. You'll create a user interface comprising a 'CardView', 'EditText' for entering the phone number, and a 'Button' to initiate the call. The tutorial will guide you through handling permissions to make phone calls, implementing onClick functionality for the Button to trigger the call action, and ensuring the app behaves correctly throughout the process. This implementation provides practical insights into integrating telephony features seamlessly within your Kotlin-based Android applications.
Submitted on July 07, 2024

To create an Android app in Kotlin that allows making a call from a given number using a ‘CardView’, ‘EditText’, and ‘Button’, follow these steps:

Step-by-Step Implementation:

  1. Create a New Android Project:

    • Open Android Studio and create a new project with an Empty Activity template.
  2. Modify activity_main.xml:

    • Open res/layout/activity_main.xml and add a CardView, EditText for entering the phone number, and a Button to initiate the call.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:padding="16dp"
            android:elevation="4dp">

            <EditText
                android:id="@+id/editTextPhone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Enter phone number"
                android:inputType="phone"/>

            <Button
                android:id="@+id/btnCall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="Call"
                android:onClick="makePhoneCall"/>

        </androidx.cardview.widget.CardView>

</RelativeLayout>

    

3.Request Call Permission

  • Open ‘AndroidManifest.xml’ and add the permission to make phone calls:
    
    	<uses-permission android:name="android.permission.CALL_PHONE" />
    

4. Implement MainActivity.kt

  • Open ‘MainActivity.kt’ and implement the logic to handle making a phone call using the entered phone number.

    package com.example.makeacall

    import android.Manifest
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.net.Uri
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.EditText
    import android.widget.Toast
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class MainActivity : AppCompatActivity() {

        private lateinit var editTextPhone: EditText

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

            editTextPhone = findViewById(R.id.editTextPhone)
        }

        fun makePhoneCall(view: android.view.View) {
            val phoneNumber = editTextPhone.text.toString().trim()

            if (phoneNumber.isNotEmpty()) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.CALL_PHONE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.CALL_PHONE),
                        REQUEST_CALL_PERMISSION
                    )
                } else {
                    startCall(phoneNumber)
                }
            } else {
                Toast.makeText(this, "Please enter a phone number", Toast.LENGTH_SHORT).show()
            }
        }

        private fun startCall(phoneNumber: String) {
            val callIntent = Intent(Intent.ACTION_CALL)
            callIntent.data = Uri.parse("tel:$phoneNumber")

            try {
                startActivity(callIntent)
            } catch (ex: SecurityException) {
                ex.printStackTrace()
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
            }
        }

        companion object {
            private const val REQUEST_CALL_PERMISSION = 1
        }
    }

    

Explanation:

  • ‘activity_main.xml’: Contains a CardView wrapping an EditText for phone number input and a Button for making the call.
  • ‘MainActivity.kt’:
    • ‘onCreate()’: Initializes the EditText and sets up the UI.
    • ‘makePhoneCall()’: Called when the ‘Call’ button is clicked. It retrieves the phone number from the EditText, checks for ‘CALL_PHONE’ permission, and either requests it or initiates the call.
    • ‘startCall()’: Sets up an Intent to make a phone call using the ‘ACTION_CALL’ action and the phone number provided.
    • ‘Companion Object’: Contains a constant ‘REQUEST_CALL_PERMISSION’ to manage the request code for permission handling.

Testing:

  • Run the app on an emulator or a physical device.
  • Enter a valid phone number in the ‘EditText’ and click the "Call" button.
  • Ensure the app requests permission to make phone calls and then initiates the call using the entered phone number.

This implementation provides a simple way to create an Android app in Kotlin that allows users to make a phone call from a given number using a ‘CardView’, ‘EditText’, and ‘Button’. Adjustments can be made based on specific requirements or additional features needed in your app.

Make A Call from Android App In Java Version

An Android app in Java that allows making a phone call from a given number using a CardView, EditText, and Button.


    package com.example.makeacall;

    import androidx.appcompat.app.AppCompatActivity;
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        private EditText editTextPhone;
        private static final int REQUEST_CALL_PERMISSION = 1;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            editTextPhone = findViewById(R.id.editTextPhone);
        }

        public void makePhoneCall(View view) {
            String phoneNumber = editTextPhone.getText().toString().trim();

            if (!phoneNumber.isEmpty()) {
                if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL_PERMISSION);
                } else {
                    startCall(phoneNumber);
                }
            } else {
                Toast.makeText(this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
            }
        }

        private void startCall(String phoneNumber) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + phoneNumber));

            try {
                startActivity(callIntent);
            } catch (SecurityException e) {
                e.printStackTrace();
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_CALL_PERMISSION) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    String phoneNumber = editTextPhone.getText().toString().trim();
                    startCall(phoneNumber);
                } else {
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }