Monday, March 22, 2010

How to Detect Call State

Some applications need to do clever things whenever there’s an incoming or outgoing call. There’s a great example of this in the source code for ‘five’ (an app providing remote access to your PC’s music collection) where the music PlaylistService listens for incoming calls so it can temporarily pause playback…


TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

and…

private PhoneStateListener mPhoneListener = new PhoneStateListener()
{
public void onCallStateChanged(int state, String incomingNumber)
{
try {
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
...
break;

case TelephonyManager.CALL_STATE_OFFHOOK:
...
break;

case TelephonyManager.CALL_STATE_IDLE:
...
break;
default:
Log.d(TAG, "Unknown phone state=" + state);
}
} catch (RemoteException e) {}
}
};

In many applications, the next stage is to do something based on an incoming telephone number. The number is given by the String incomingNumber parameter shown above.

Also don’t forget the following in your manifest…