Recipe 4.5 Auto-Answering an Incoming Call

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

Recipe 4.3 showed you how to monitor the state of the phone to detect whether it is ringing, off hook, or idle. Another useful behavior is answering a call automatically when the phone rings. For example, you might want to write an application that allows the user to automatically answer a call (only for some specific phone numbers) when the user is busy (such as when he is driving). This recipe demonstrates how to do that.

Solution

To programmatically answer an incoming call, your application simply needs to emulate the device with a Bluetooth headset attached. When an incoming call is detected, you fire an Intent object to simulate the user pressing the button on the Bluetooth headset.

First, to detect an incoming call, you need a BroadcastReceiver class to monitor for changes in phone state (as discussed in Recipe 4.3). The following IncomingCallsReceiver class is a subclass of the BroadcastReceiver class:

package net.learn2develop.autocalls; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; import android.view.KeyEvent; public class IncomingCallsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (!intent.getAction().equals( "android.intent.action.PHONE_STATE")) ...

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.