Friday, February 10, 2012

How to recognize an incoming phone call through code in Android?

A simple code-snippet to recognize incoming phone calls in your apps. 

public class ReactOnIncomingCall extends Activity {
   /** Used to recognize Messages from the
  * myPhoneStateChangedHandler. */
   final int PHONECALLSTATE_RECONGNIZE_ID = 0x539;
   
   /** Will notify us on changes to the PhoneState*/
   PhoneStateIntentReceiver myPsir = null;

  /** This Handler will react on the messages the
   * we made our PhoneStateIntentReceiver myPsir
   * notify us on. */
  Handler myPhoneStateChangedHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

     // Recognize the Message by its what-ID
     if(msg.what == PHONECALLSTATE_RECONGNIZE_ID){

        /* Our PhoneStateIntentReceiver myPsir
       * now contains some recent data, we can grab. */
        Phone.State myState = myPsir.getPhoneState();

        // Put the Info to the logger for debugging
        Log.d("PhoneCallStateNotified", myState.toString());

        if(myState == Phone.State.RINGING){
         // Celebrate =D
        }      
     }
    }
  };
   
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
   // Set some simple layout
    super.onCreate(icicle);
    setContentView(R.layout.main);

   
    /* Create a new PhoneStateIntentReceiver
   * that will pass messages to the handler h
   * as it receives Intents we make it notify
   * us below*/
    this.myPsir = new PhoneStateIntentReceiver(this, 
      myPhoneStateChangedHandler);
   
    /* As we want to get notified on changes
   * to the Phones-State we tell our
   * PhoneStateIntentReceiver myPsir,
   * that we wan to get notified with the ID
   * (PHONECALLSTATE_RECONGNIZE_ID) we pass to him
   */
    this.myPsir.notifyPhoneCallState(PHONECALLSTATE_RECONGNIZE_ID);
    
    /* Register the Intent with the system. */
    this.myPsir.registerIntent();
  }
}

No comments:

Post a Comment