我想要实现的是当我从我的主要活动中进行第二次活动时停止播放音乐(此功能和音乐确实停止)但是当我按下后退按钮返回主要活动音乐时似乎没有重新开始。我怎样才能让它重新开始,或者在第二次活动时可能会暂停音乐,并在返回主要活动时恢复。
以下是我的代码,其中音乐在进入下一个活动时停止,但在返回主要活动时没有播放:
public class MainActivity extends Activity implements OnClickListener{
public static MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.music_a);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
player.stop();
}
});
}
protected void onPause() {
if (this.isFinishing()){
player.stop();
Toast.makeText(MainActivity.this, "BYE", Toast.LENGTH_LONG).show();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
else {
}
}
super.onPause();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
这是我的第二项活动(我是否也需要在这里放一些东西?)
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
}
}
谢谢
答案 0 :(得分:3)
您必须在第一个活动上致电onResume
才能继续播放音乐
@Override
protected void onPause() {
super.onPause();
// stop the music
}
@Override
protected void onResume() {
super.onResume();
// play the music here
}
答案 1 :(得分:0)
只需删除您的代码即可从oncreate播放并开始在onResume中播放歌曲
try {
if (player != null) {
player.start();
} else {
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.meintenu);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edit:
在按钮中单击
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
player.stop();
player.release();
player=null;
答案 2 :(得分:0)
当您转到下一个活动并获取音乐的当前位置时,暂停音乐
homeMusic.pause();
position=homeMusic.getCurrentPosition();
然后添加onRestart
方法,
@Override
protected void onRestart() {
super.onRestart();
homeMusic.seekTo(position);
homeMusic.start();
homeMusic.setLooping(true);
}