Search code examples
androidphone-call

How can I find out when on android 2.3+ a phone call starts and stops?


I need my app to find out when a phone call is taking place.

It should work on when another phone is being called and also when a call is answered. I just need my app to get notified of exactly when the connection starts and when it stops (not the dialing, ringing, etc.).

Is this somehow possible?


Solution

  • You can use broadcast class to achieve this as below:

    public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
    
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new CustomPhoneStateListener(context),
                PhoneStateListener.LISTEN_CALL_STATE);
        }
    }
    
    class CustomPhoneStateListener extends PhoneStateListener {
    
        // private static final String TAG = "PhoneStateChanged";
        Context context; // Context to make Toast if required
    
        public CustomPhoneStateListener(Context context) {
            super();
            this.context = context;
        }
    
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
    
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
    
            case TelephonyManager.CALL_STATE_IDLE:
                //WHEN PHONE WILL BE IDLE       
            break;
    
            case TelephonyManager.CALL_STATE_OFFHOOK:
                // when Off hook i.e in call
            break;
    
            case TelephonyManager.CALL_STATE_RINGING:
                // when Ringing
            break;
    
            default:
            break;
            }
        }
    }
    

    Hope this will help you.