我的活动有背景音乐媒体播放器。我想暂停它并在新活动开始时重置它,并在活动销毁时停止它。
我这样做了:
@Override
protected void onResume() {
if(!continiue){
continiue=true;
try{
if (m != null) {
m=new MediaPlayer();
m.reset();
m = MediaPlayer.create(this, R.raw.menu);
m.start();
m.setLooping(true);
}
else{
m.start();
}
}
catch(Exception e){
e.printStackTrace();
}
super.onResume();
}
}
@Override
protected void onStop() {
try{
if(m!=null){
m.stop();
m.release();
}
}
catch(Exception e){
}
super.onStop();
}
@Override
protected void onPause() {
try{
if(m.isPlaying()){
m.pause();
}
}
catch(Exception e){
}
super.onPause();
}
这很好用。现在我想添加另一个活动,但我希望音乐仅在此特定活动打开时继续播放。我怎么能这样做?
答案 0 :(得分:1)
仅为音乐播放创建一个单独的类,并从“活动”中对其进行规则。像这样:
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
public class BackgroundMusicPlayer {
private static MediaPlayer mp = null;
private static int playingResId;
public static boolean isSoundTurnedOff;
private static boolean isPaused;
/** Stop old sound and start new one */
public static void play(Context context, int resIdToPlay) {
if (isSoundTurnedOff || context==null)
return;
if (mp != null && playingResId==resIdToPlay) {
if (isPaused)
mp.start();
isPaused = false;
return;
}
stop();
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
context.sendBroadcast(i);
playingResId = resIdToPlay;
mp = MediaPlayer.create(context, resIdToPlay);
if (mp != null) {
mp.setLooping(true);
mp.start();
} else
Log.e("BackgroundMusicPlayer","Cant create MediaPlayer. MediaPlayer.create(context: "+context+", resIdToPlay: "+resIdToPlay+") returns null");
}
/** Stop the music */
public static void stop() {
if (mp != null) {
isPaused = false;
playingResId = 0;
mp.stop();
mp.release();
mp = null;
}
}
public static void pause() {
if (mp != null){
mp.pause();
isPaused = true;
}
}
public static void resume() {
if (mp != null && isPaused){
mp.start();
isPaused = false;
}
}
}