Skip to content Skip to sidebar Skip to footer

Listen To Change Of Phone State State - Android

I am currently trying to create a simple app that records how many minutes you have spent calling and then warn you when you are close to your free minutes. At this point I have c

Solution 1:

Yes, you need to use onCallStateChanged method.

put this lines in your onCreate() method,it will initialize object of TelephonyManager and will setup listener for you.

TelephonyManagertManager= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
ListenToPhoneStatelistener=newListenToPhoneState()
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

class definition of innerclass ListenToPhoneState will be looking like this,

privateclassListenToPhoneStateextendsPhoneStateListener {

        boolean callEnded=false;
        publicvoidonCallStateChanged(int state, String incomingNumber) {
            
            switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
                UTILS.Log_e("State changed: " , state+"Idle");


                if(callEnded)
                {
                    //you will be here at **STEP 4**//you should stop service again over here
                }
                  else
                  {
                    //you will be here at **STEP 1**//stop your service over here,//i.e. stopService (new Intent(`your_context`,`CallService.class`));//NOTE: `your_context` with appropriate context and `CallService.class` with appropriate class name of your service which you want to stop.

                  }

                
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                UTILS.Log_e("State changed: " , state+"Offhook");
                    //you will be here at **STEP 3**// you will be here when you cut call
                callEnded=true;
                break;
            case TelephonyManager.CALL_STATE_RINGING:
                UTILS.Log_e("State changed: " , state+"Ringing");
                    //you will be here at **STEP 2**break;
                

            default:
                break;
            }
        }

    }

Explaination: While the call,your listener will go through following states,

Step 1: TelephonyManager.CALL_STATE_IDLE

initially your call state will be idle that is why the variable callEnded will have the value false.

Step 2: TelephonyManager.CALL_STATE_RINGING

now you are waiting for the receiver person to receive your call

Step 3: TelephonyManager.CALL_STATE_OFFHOOK

you cut the call

Step 4: TelephonyManager.CALL_STATE_IDLE

idle again

NOTE: If you don't want to know when the call ends and what should be done after ending the call then just remove callEnded variable and stop the service whenever you enter in the block of TelephonyManager.CALL_STATE_IDLE

I hope it will be helpful !!

Post a Comment for "Listen To Change Of Phone State State - Android"