Amazon Gift Cards

Thursday, January 22, 2009

Get Phone State When Someone is calling using BroadcastReceiver Example

In this article we shall try to listen to the phone state when contacts are calling us.

First of all we need to set our Manifest file to listen to the Phone State, to do that we need to edit our it.
  <receiver android:name=".ServiceReceiver">
      <action android:name="android.intent.action.PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE">

Here you can see that we created a receiver xml node inside our application and have the java class ServiceReceiver to listen to it. What it would listen to is the PHONE_STATE and thus we need the permission of READ_PHONE_STATE. Then our ServiceReceiver Class would look like this.

public class ServiceReceiver extends BroadcastReceiver {
  public void onReceive(Context context, Intent intent) {
    MyPhoneStateListener phoneListener=new MyPhoneStateListener();
    TelephonyManager telephony = (TelephonyManager) 

For the full class including the imports, please download the files below. In here we have another class called MyPhoneStateListener, which would be shown at the bottom. What this class would do is execute the phoneListener when the telephony.listen has received a LISTEN_CALL_STATE.

public class MyPhoneStateListener extends PhoneStateListener {
  public void onCallStateChanged(int state,String incomingNumber){
    case TelephonyManager.CALL_STATE_IDLE:
      Log.d("DEBUG", "IDLE");
    case TelephonyManager.CALL_STATE_OFFHOOK:
      Log.d("DEBUG", "OFFHOOK");
    case TelephonyManager.CALL_STATE_RINGING:
      Log.d("DEBUG", "RINGING");

What we have is a function called onCallStateChanged which would be fired when the LISTEN_CALL_STATE dispatches it. The states are either, ringing(CALL_STATE_RINGING), answers (CALL_STATE_OFFHOOK), or hang up/end call (CALL_STATE_IDLE). To see the logs in eclipse. Go to Window -> Show View -> Other -> Android -> LogCat

Hope it helps.



Update History
   Jan 17, 2012 - Visual Update
Post a Comment