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 :
<a href="https://medium.com/media/142f6149308221649084ba17707b3fce/href">https://medium.com/media/142f6149308221649084ba17707b3fce/href</a>
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 :
<a href="https://medium.com/media/9de394597713a02a0ce67d2731f68c18/href">https://medium.com/media/9de394597713a02a0ce67d2731f68c18/href</a>
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 :
<a href="https://medium.com/media/cf4bb65aafc47e040e4e0e07fe11afbb/href">https://medium.com/media/cf4bb65aafc47e040e4e0e07fe11afbb/href</a>
To manage the result of this request, we need to override the onRequestPermissionsResult and to check if permission has been granted :
<a href="https://medium.com/media/ffaf0ad2d15e9bb0f230f2581484d467/href">https://medium.com/media/ffaf0ad2d15e9bb0f230f2581484d467/href</a>
Finally, the complete code of the MainActivity class will have the following form :
<a href="https://medium.com/media/5d1cb742255950cbc8dd1424863302ed/href">https://medium.com/media/5d1cb742255950cbc8dd1424863302ed/href</a>
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 :
You can also visit the SSaurel’s Blog to discover written Java and Android tutorials : https://www.ssaurel.com/blog