我有一个媒体播放器,可以在下面的活动中播放音乐。问题是,音乐转移到所有其他活动,这很好。但是当我开始音乐,去另一个活动,然后回到下面的活动,togglebutton已经从开启变为关闭。因此,如果我点击togglebutton,即使音乐仍在播放,音乐也会重新开始,所以现在音乐一次播放两次!如何让togglebutton知道音乐正在播放,所以当我回到活动时,togglebutton是" on"从最开始?它"关"默认情况下。
public class SpelaActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spela);
final MediaPlayer mediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.ljudfil);
ToggleButton musikknapp = (ToggleButton) findViewById(R.id.togglemusik);
musikknapp.setOnCheckedChangeListener (new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
mediaPlayer.start();
} else {
mediaPlayer.pause();
}
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
}
}
答案 0 :(得分:0)
您需要保存ToggleButton状态。 试试这段代码:
public class MainActivity extends Activity {
private ToggleButton toggleButton;
private static Bundle bundle = new Bundle();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
}
@Override
public void onPause() {
super.onPause();
bundle.putBoolean("ToggleButtonState", toggleButton.isChecked());
}
@Override
public void onResume() {
super.onResume();
toggleButton.setChecked(bundle.getBoolean("ToggleButtonState",false));
}
答案 1 :(得分:0)
添加这些条件if(!mediaPlayer.isPlaying())
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
} else {
if(!mediaPlayer.isPlaying())
mediaPlayer.pause();
}
}
答案 2 :(得分:0)
管理以让媒体播放器在后退按钮点击时停止:
final ToggleButton togglemusik = (ToggleButton) findViewById(R.id.togglemusik);
mp = MediaPlayer.create(this, R.raw.ljudfil);
togglemusik.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (togglemusik.isChecked()) {
mp.start();
} else {
mp.pause();
}
}
});
}
@Override
public void onPause() {
super.onPause();
if (mp !=null) {
mp.release();
mp = null;
}
}