user1163234 user1163234 - 2 months ago 11
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">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>



public class IncomingBroadcastReceiver extends BroadcastReceiver {

@Override
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

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;
    @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.

Comments