Introduce PhoneStateListener in your application like this:
private PhoneStateListener mPhoneListener = new PhoneStateListener() { public void onCallStateChanged(int state, String incomingNumber) { try { switch (state) { case TelephonyManager.CALL_STATE_RINGING: pauseStream(); break; case TelephonyManager.CALL_STATE_OFFHOOK: break; case TelephonyManager.CALL_STATE_IDLE: resumeStream(); break; default: } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } };
Then you need to install it in your onCreate () or in your onStartCommand () method in case of service:
radioStream.setAudioStreamType(AudioManager.STREAM_MUSIC); radioStream.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer stream) { telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); telephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); isMusicPlaying = true; isServiceRunning = true; stream.start(); } }); try { radioStream.prepare(); } catch (IllegalStateException e1) { e1.printStackTrace(); streamErrorHandler(); } catch (IOException e1) { e1.printStackTrace(); streamErrorHandler(); }
and you can implement your version of the following methods:
public static void pauseStream() { if (isServiceRunning) { if (radioStream.isPlaying()) { isMusicPlaying = false; radioStream.pause(); } } else { Log.i(TAG, "service isn't running"); } } public static void resumeStream() { if (isServiceRunning) { if (!radioStream.isPlaying()) { isMusicPlaying = true; radioStream.start(); } } else { Log.i(TAG, "service isn't running"); } }
radioStream is your static MediaPlayer object. I use this in a service, so you can leave isServiceRunning , but this should work for any case.
source share