The Android phone device is always in one of the three states: idle (when no calls), ringing (during incoming call), or off hook (during a call). You can monitor these states of the phone and build some interesting applications. For example, send a SMS to the caller whenever you are driving or disconnect the calls automatically whenever there is an unknown number or play a voice message. This article will show you how to monitor the state of your phone.
To programatically answer an incoming call, we need to detect an incoming call and to do that we need a BroadcastReceiver class to monitor the changes in phone state. The following receiver class CallStateReceiver is a subclass of the BroadcastReceiver class:
public class CallStateReceiver extends BroadcastReceiver
public void onReceive(Context context, Intent intent)
String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String phonenumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
To exlain this further, whenever a change in phone state is detected, we first check if it is the phone ringing using the EXTRA_STATE constant. If it is EXTRA_STATE_RINGING, then we can get the incoming phone number using the EXTRA_INCOMING_NUMBER constant. With this information, we can determine if our app should automatically answer the call or take whatever action as per your business logic. To automatically answer the call, we do that using an Intent object with the ACTION_MEDIA_BUTTON action, passing it an extra KeyEvent object. And lastly we send the broadcast using the send-OrderedBroadcast() method. This enables the phone to automatically answer an incoming call based on the phone number we set in our app.
To monitor changes to phone state, add the READ_PHONE_STATE permission to the AndroidManifest.xml file and also register the BroadcastReceiver class.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<receiver android:name=".CallStateReceiver" >
<action android:name="android.intent.action.PHONE_STATE" />
The above code snippet shows that we can answer the incoming call programmatically, but we cannot terminate an incoming call. Even if we add CALL_PRIVILEGED permission to the AndroidManifest.xml file, it will not work since this is not available to third party apps avaialable through play store since it is only available to system apps.