Detecting Outgoing Call and Call Hangup Event in Android

Detecting outgoing call and call hangup event in android

You should create a BroadcastReceiver:

public class CallReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {

// Phone number
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

// Ringing state
// This code will execute when the phone has an incoming call
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {

// This code will execute when the call is answered or disconnected
}

}
}

You should register you application to listen to these intents in the manifest:

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

How to detect when phone is answered or rejected

in your onReceive:

PhoneStateChangeListener pscl = new PhoneStateChangeListener();
TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(pscl, PhoneStateListener.LISTEN_CALL_STATE);

separate class:

private class PhoneStateChangeListener extends PhoneStateListener {
public static boolean wasRinging;
String LOG_TAG = "PhoneListener";
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.i(LOG_TAG, "RINGING");
wasRinging = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(LOG_TAG, "OFFHOOK");

if (!wasRinging) {
// Start your new activity
} else {
// Cancel your old activity
}

// this should be the last piece of code before the break
wasRinging = true;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(LOG_TAG, "IDLE");
// this should be the last piece of code before the break
wasRinging = false;
break;
}
}
}

All you need to do is write some code to check if the previous state was 'ringing'.
If the current state is idle and the previous state was ringing, they cancelled the call.
If the current state is offhook and the previous state was ringing, they answered the call.

How can I know when a call end?

use TelephonyManager

public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
break;
}

System.out.println("state-:: " + stateString);
}


Related Topics



Leave a reply



Submit