0
我试图停止音乐时,用户离开应用程序或点击(home键),我的应用程序播放音乐,即使它是在后台,我怎么可以停止音乐,如果用户单击主页按钮?如果用户返回,音乐将再次播放? 我的代码:如何停止音乐,如果在后台应用程序
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.vaporv2);
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mediaPlayer.start();
}
});
//toggle off and on :
MusicButton = (ToggleButton) findViewById(R.id.toggleButton);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (MusicButton.isChecked() && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
});
这种行为通常是* *对称。这意味着它们在相反的生命周期事件中执行。你在'onResume'开始做什么?停在'onPause'上。你在'onStop'上停止了什么吗?你应该启动它在'onStart' – Pelocho
'我试图停止音乐时,用户离开应用程序或点击(home键),我的应用程序播放音乐,即使它是在后台,我怎么可以停止音乐,如果用户点击主页按钮?如果用户返回时,音乐播放again'-这就是OP问我根据它虽然可能不是实际的功能性回答。 –