You must have seen several apps which opens a dialer with a specific number or even directly make a call to them. This functionality is quite easy to implement and very useful.
Let us look at the different ways to do the required task.
1) If you have a TextView which is displaying a phone number and you want to call on that number on a tap then this can be achieved by adding the autoLink attribute to the TextView.
1 |
android:autoLink="phone" |
But this one comes with a drawback that it doesn’t work for all kind of phone numbers. For example, a phone number of 11 numbers won’t work with this option. The solution is to prefix your phone numbers with the country code (09876543210 won’t work but +1569876543210 will work).
This doesn’t even need permission. Just add the attribute and you are good to go.
2) You can do the same programmatically also. The Intent.ACTION_DIAL will take you to the dialer screen all you need to do is add the phone number in the data.
1 2 3 |
Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:9876543210")); startActivity(intent); |
The ‘tel:’ prefix is required, otherwise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.
3) If you want to directly make a call then this needs a CALL_PHONE permission. Add the permission in your AndroidManifest and change the ACTION_DIAL to ACTION_CALL in the above method.
1 |
<uses-permission android:name="android.permission.CALL_PHONE" /> |
1 2 3 |
Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:0123456789")); startActivity(intent); |
Thank you very much. This is Vedesh Kumar signing off.