Android: How to stop this music already?
I have created an application and with some background music.
Result = SUCCESS
Problem is.. -.- if app receives a call, music is still playing and plays instead of the user's original ringtone. Plus if "Home" button is selected on the phone. Activity exits but the music is still running?
I managed to quit the music if the "Back" button on the phone is selected.
other than that music runs 24/7.
What I have used is.
A menu option in the application that when the user selected "Menu" a list of options pop up and an option to choose "Settings..." If the user selects "Settings..." a preference dialogue pops up to check or uncheck music (ON/OFF) Result = SUCCESS
The music plays throughout the application, from activity to activity.
This is my media player code in开发者_StackOverflow社区 my application.
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.bgmusic);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
finish();
Music.stop(this);
return true;
}
return super.onKeyDown(keyCode, event);
}
This is my music.java
public class Music {
private static MediaPlayer mp = null;
/** Stop old song and start new one */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
}
}
/** Stop the music */
public static void stop(Context context) {
if (mp != null) {
mp.stop();
mp.pause();
mp.release();
mp = null;
}
}
}
anyone have a clue?
You need to call
Music.stop(this);
in the onPause method. This may have the effect of an instant glitch, when switching from one of yours activities to another.
Read also this question and the accepted answer.
精彩评论