Recognize incoming PhoneCalls 
What you will learn: You will learn how to recognize on incoming PhoneCalls by using a PhoneStateIntentReceiver. Possible scenario is, to disable your music-player, when there is an incoming Phone-Call.
Difficulty: 2 of 5

What it will look like:
Unfortunately nothing to see here 
Description:
We will create an PhoneStateIntentReceiver that sends Messages to a Handler when the PhoneState changes. Take a look at the heavily commented example-implementation (The actual registering takes place in the onCreate()-method):
Using java Syntax Highlighting
- package org.anddev.android.reactonincomingcall;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.telephony.Phone;
- import android.telephony.PhoneStateIntentReceiver;
- import android.util.Log;
- 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();
- }
- }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4
Regards,
plusminus







