Detecting incoming and outgoing calls in Android

Detecting incoming and outgoing calls in Android can be realized in several ways. One of the possibilities is to use a custom PhoneStateListener which can be attached to the TelephonyManager in your onReceive() function of the custom BroadcastReceiver. This is a “clean” way, beacause the BoradcastReceiver object is destroyed as soon as the onReceive() function is left. But if you just want to do some little stuff, you can implement your logic directly in the onReceive() function. Here how it works.

For detecting outgoing calls you need to register android.permission.PROCESS_OUTGOING_CALLS permission. The android.intent.action.NEW_OUTGOING_CALL will be broadcasted when an outgoing call is initiated. Use an extra string variable Intent.EXTRA_PHONE_NUMBER to detect the outgoing number.

For incoming call you need to register your BroadcastReceiver for the action android.intent.action.PHONE_STATE. This will be broadcasted when the phone state is changed. The receiving intent contains an extra string variable TelephonyManager.EXTRA_STATE. If this state is TelephonyManager.EXTRA_STATE_RINGING then there will be another extra string variable (! only if state = TelephonyManager.EXTRA_STATE_RINGING !). Use TelephonyManager.EXTRA_INCOMING_NUMBER to read the incoming phone number.

And now the corresponding code. In your manifest.xml add following lines for permissions:

 
 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />

Furthermore add your BroadcastReceiver:

 
<receiver android:name="YourBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE"></action>
        <action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>
    </intent-filter>
</receiver>

Your code would look like this:

public class YourBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
   Bundle bundle = intent.getExtras();
   if (bundle == null)
      return;
   String phoneNumber = null;
	
   // Incoming call
   String state = bundle.getString(TelephonyManager.EXTRA_STATE);
   if ((state != null) 
        &amp;amp;&amp;amp; (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))) {
	   phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);	
	   // Here: do something with the number	         
   }
   // Outgoing call
   else if (state == null) {		
      phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
      // Here: do something with the number
   }  
 }	
}