0

I am using this code, to listen the state of phone. when call arrives it pauses the media player but as soon as I pick up the call it starts play again from listening speaker(not from ringer). and I also tried with removing the mediaPlayer.start() from case TelephonyManager.CALL_STATE_IDLE: in this case it works fine but it doesn't start(resume) again. Is there any flag available to do that?

 private final PhoneStateListener phoneListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    try {
        switch (state) {
        case TelephonyManager.CALL_STATE_RINGING: 
            Toast.makeText(context, "Call is Coming",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
        break;

        case TelephonyManager.CALL_STATE_OFFHOOK: 

        break;

        case TelephonyManager.CALL_STATE_IDLE: 
            mediaPlayer.start();

        break;

        default: 
        }
        } catch (Exception ex) {
            mediaPlayer.release();
        }
    }
};

}

or Is there any other way to do that?

T_V
  • 17,440
  • 6
  • 36
  • 48
  • Im not too familiar with the Telephonymanager, but I would suggest you use a Soundpool instead of the MediaPlayer for way better performance. – Philipp Jahoda Aug 09 '13 at 07:33
  • I would put something in the default case in order to see if you are handling all the cases – Snake Sanders Aug 09 '13 at 07:40
  • this question is similar to this http://stackoverflow.com/questions/5610464/stopping-starting-music-on-incoming-calls – artsylar Aug 09 '13 at 07:50

1 Answers1

1

Try this:

PhoneStateListener phoneStateListener = new PhoneStateListener() {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        if (state == TelephonyManager.CALL_STATE_RINGING) {
            //Incoming call: Pause music
        } else if(state == TelephonyManager.CALL_STATE_IDLE) {
            //Not in call: Play music
        } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
            //A call is dialing, active or on hold
        }
        super.onCallStateChanged(state, incomingNumber);
    }
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
    mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
Vettiyanakan
  • 7,957
  • 6
  • 37
  • 55