📞

How to Make Phone Calls in an Android App

Jul 1, 2024

How to Make Phone Calls in an Android App

Overview

In this tutorial, we learn how to make phone calls in an Android application by requesting necessary permissions and using intents. Make sure to have a foundational understanding of Android permissions and intents, which are covered in previous tutorials.

Steps to Make a Phone Call

1. Requesting Permissions

  • Go to the Android manifest file: Located under the manifest folder.
  • Request permission: Add the following line to request the necessary permission to make phone calls. <uses-permission android:name="android.permission.CALL_PHONE" />
  • Additional resource: Check out the video on requesting permissions if you need more information on this step.

2. Setting Up the Main Activity

  • Navigate to MainActivity.java:
    • Created a CardView to be used as a button for initiating the call (refer to another tutorial for setting up CardView).
    • Only initiate the call when the button is pressed, not when the app is launched.

3. Creating the Call Intent

  • Initialize Intent: Intent callIntent = new Intent(Intent.ACTION_CALL);
  • Set Data (Phone Number): callIntent.setData(Uri.parse("tel:+123456789"));
    • Replace +123456789 with the actual phone number you want to call. This example uses a random number for demonstration purposes.

4. Checking Permissions at Run-time

  • Check if permission is granted: if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL); }
    • Ensure to replace REQUEST_CALL with your specific request code.
  • Handling the result in onRequestPermissionsResult method:
    • Process the user's response to the permission dialog.

5. Making the Phone Call

  • Start the activity if permission is granted: startActivity(callIntent);

Running the App

  • Testing:
    • When tapping on the CardView, the app will ask for permission if not yet granted.
    • If permission is denied, the app will continue to request it until granted.
    • Once permission is granted, the app will place the call to the specified number.

Conclusion

  • Summary: By following this tutorial, you can integrate phone call functionality in your Android app.
  • Questions: Post them in the comments below.
  • Reminder: Don't forget to subscribe to the channel for more tutorials.