Recipe 4.1 Calling from Your Application

Android Versions
Level 1 and above
Permissions
android.permission.CALL_PHONE
Source Code Download from Wrox.com
MakeCalls.zip

If you are developing an application for a business that provides phone support, why not build that capability directly into the application? For example, suppose the user is currently using your application and needs to make a call to the company for help; in this case, your application can directly dial the phone number. This recipe shows you how.

Solution

To enable users to dial a phone number directly from your application, you can use an Intent object by passing it the ACTION_DIAL action, together with the URI in the following format: tel:<phone_number>:

package net.learn2develop.makecalls;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String phoneNumber = "+13175723496";
        Intent i = new
                Intent(android.content.Intent.ACTION_DIAL, 
                        Uri.parse("tel:+" + phoneNumber));        
        startActivity(i);
    }

}

The preceding code snippet causes the Phone application to dial the specified number (see Figure 4-1). To place the call, the user needs to physically press the call button.

If you want the Phone application to directly place the call for users ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.