Android
    About Lesson

    Initiating phone calls is a common feature in many applications. Whether it’s for customer service, personal reminders, or communication, phone call functionality can greatly enhance the user experience. In this blog post, we’ll explore how to initiate phone calls in Android using Intent.

     

    Step 1: Setting Up the Intent

    The first step in making a phone call using Android is to set up an Intent. An Intent in Android is a software mechanism for describing a desired action, like opening a web page, sending an email, or in our case, making a phone call.

    Here’s a simple example of how to create an Intent for making a phone call:

    String phoneNumber = "123456890";
    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:" + phoneNumber));

     

    In this code, Intent.ACTION_CALL is the action that will be performed by the Intent. The setData method sets the data URI that will be acted upon. In this case, we’re setting it to tel: followed by the phone number which represents a telephone number.

     

    Step 2: Starting the Call Activity

    The final step is to start an activity with the Intent. This will open the phone dialer with the phone number filled in.

    Here’s how to start the activity:

    startActivity(callIntent);

    In this code, the startActivity method is then used to start the activity.

     

    Step 3: Handling Permissions

    To make a phone call, your app needs the CALL_PHONE permission. This should be declared in your app’s manifest file like this:

    <uses-permission android:name="android.permission.CALL_PHONE" />

     

    Additionally, starting from Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app’s functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app’s Settings screen.

    Here’s how to request the CALL_PHONE permission at runtime:

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
    }

    In this code, ContextCompat.checkSelfPermission is used to check if the app has the CALL_PHONE permission, and ActivityCompat.requestPermissions is used to request the permission if it’s not already granted. MY_PERMISSIONS_REQUEST_CALL_PHONE is a constant that’s used as the request code for the permission request.