I am using android.media.MediaPlayer object to play audio files in my app. Everything works fine but when a phone call comes while a song is playing the app doe
Introduce a PhoneStateListener in your Application like so:
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 set it up in your onCreate() or in your onStartCommand() method in case of a 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 am using this within a service so you can drop out the isServiceRunning but this should work for anyone's case.