我使用切换按钮播放音频文件。当我选中切换按钮时,app会播放音乐。当音乐结束时,我希望它自动取消选中切换按钮。我能怎么做 ? 这是我演奏的音乐方法:
MediaPlayer mp = null;
protected void playmusic(String theText) {
if (mp != null) {
mp.reset();
mp.release();
}
if (theText.length() > 2) {
mp = MediaPlayer.create(this, Uri.parse(theText));
} else { mp = MediaPlayer.create(this, R.drawable.afart11);
}
mp.start();
}
这是我的切换按钮:
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(this);
...
...
case R.id.toggleButton1:
if (tg.isChecked()) {
playmusic(Setting.set);
else {
mp.stop();
}
答案 0 :(得分:2)
将onCompletionListener设置为MediaPlayer
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp){
tg.setChecked(false);
}
});
答案 1 :(得分:1)
实施OnCompletionListener
并致电mp.setOnCompletionListener(this)
。歌曲结束时会调用回调方法onCompletion(MediaPlayer mp)
。
public class YourActivity extends Activity implements OnCompletionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//media player code
mp.setOnCompletionListener(this);
}
@Override
public void onCompletion(MediaPlayer mp) {
//your code when song completes
}
}