user1163234 user1163234 - 1 year ago 49
Android Question

How to detect when phone is answered or rejected

I managed to prepare an activity when the phone is ringing. Now I need to know how to cancel this activity when I anwser the phone or I reject the call.Do I call EXTRA_STATE_IDLE?EXTRA_STATE_OFFHOOK?

Any ideas?

<receiver android:name=".IncomingBroadcastReceiver">
<action android:name="android.intent.action.PHONE_STATE"/>

public class IncomingBroadcastReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
// If an incoming call arrives
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{ //Did my work }

Answer Source

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;
    public void onCallStateChanged(int state, String incomingNumber) {
            case TelephonyManager.CALL_STATE_RINGING:
                 Log.i(LOG_TAG, "RINGING");
                 wasRinging = true;
            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;
            case TelephonyManager.CALL_STATE_IDLE:
                 Log.i(LOG_TAG, "IDLE");
                 // this should be the last piece of code before the break
                 wasRinging = false;

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.