Reputation: 385
I'm developing simple android application, using Media Player to play sound. It has a button that play sounds when touched. When I touched the back button;If the sound is playing it must be stop. If the sound is not playing(finished playing) it must go back into previous activity but now it crashed with Illegal State Exception. Thank you in advance.
This is code of the button.
SoundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(),
R.raw.p3_x1_slow);
mp.reset();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
});
This where I detected the back button
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mp != null || mp.isPlaying()) {
Practice_3_detail.this.finish();
} else if (mp == null) {
finish();
} else if(mp != null && mp.isPlaying()){
//mp.pause();
finish();
} else
{
finish();
}
}
return true;
}
Upvotes: 0
Views: 1791
Reputation: 56925
Try this below code . Before finish the current activity you have to stop media player and release it's object.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
if(mp != null)
{
mp.stop();
mp.release();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 1