Smartphones are always more and more powerful but at the end, the main usage of a smartphone remains calling some people to communicate with them. In this tutorial, you are going to discover how to make calls programmatically on Android.
You can also discover this tutorial in video on YouTube :
First, we need to create a layout with an EditText view to enter the phone to call and a Button letting user to start calling when he will click on it :
Then, we must add the CALL_PHONE permission in the Android Manifest. Besides, like we target Android Marshmallow (API 23 and above), we will need to manage permissions at runtime.
Now, we can start to write the Java code of the main activity. First, we get references for the EditText and the Button views. Then, we add a ClickListener on the Button. When a user will click on the button, we will access to the phone number entered.
If the phone number field is not empty, we check of the CALL_PHONE permission has been granted for the application by creating a checkPermission method like that :
If the permission has been granted, we have just to create an Intent with the Intent.ACTION_CALL in parameter and the phone number to call.
If the permission has not been granted previously for our application, we need to request the permission by calling the static requestPermissions method of the ActivityCompat class like that :
To manage the result of this request, we need to override the onRequestPermissionsResult and to check if permission has been granted :
Finally, the complete code of the MainActivity class will have the following form :
Last step is to click on the Run Application button on Android Studio and clicking on the button to start calling the phone number entered :
To discover more tutorials on Android development don’t hesitate to subscribe to the SSaurel’s Channel on YouTube :
This channel will offer you tutorials on Android, Web Development and some others programming tips. Demo video of…
You can also visit the SSaurel’s Blog to discover written Java and Android tutorials : https://www.ssaurel.com/blog