Reputation: 119
MediaPlayer player = MediaPlayer.create(context, R.raw.background);
player.start();
The Code above is part of the current code. When I press the home key, MediaPlayer does not stop playing.
@Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (KeyCode == KeyEvent.KEYCODE_BACK) {
System.exit(0);
return true;
}
}
return super.onKeyDown(KeyCode, event);
}
I've implemented the code shown above, for when you press the Back key. Do you think that the above code is correct? Appreciate any help.
Upvotes: 0
Views: 825
Reputation: 9800
Please try with this solution:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
For more information, please read this post: Android MediaPlayer Stop and Play
Upvotes: 1
Reputation:
If your media player is running on the activity you created, you can call player.stop()
in onStop()
method.
Edit:
Your implementation is OK, but it only overrides the back key only. You have to override the home key also to stop the player
on pressing the home key. (but, use onStop()
instead as it calls when the user interface is hidden.)
Do not use System.exit()
, use finish()
instead.
If you using finish()
method (which destroys the activity), make sure that you have released the MediaPlayer
resources by calling player.release()
and nullifying the player. (i.e. player = null
)
Upvotes: 0
Reputation: 3167
Just implement below methods for this,
@Override
protected void onPause() {
super.onPause();
if(player != null)
player.stop();
}
@Override
protected void onStop() {
super.onStop();
if(player != null)
player.stop();
}
@Override
protected void onDestroy() {
super.onDestroy();
if(player != null)
player.stop();
}
Upvotes: 1