我建立了一個小的應用程序基本上振動和播放上勾選複選框的MP3文件,但不知何故,音樂不會取消選中該複選框後停止:Android的媒體播放器並沒有停止對複選框
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
final CheckBox vibrateBoxStrong = (CheckBox) findViewById(R.id.checkPowerStrong);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
vibrator.vibrate(1000);
handler.postDelayed(this, 1000);
}
};
vibrateBoxStrong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fansound1);
if(vibrateBoxStrong.isChecked()) {
handler.postDelayed(r, 100);
mediaPlayer.start();
} else {
mediaPlayer.stop();
handler.removeCallbacks(r);
vibrator.cancel();
}
}
}
);
}
}
每次'CheckBox'改變它的選中狀態,您可以創建一個新的'MediaPlayer'實例,所以你打電話'停止()'對錯誤的實例。 –
嗯好吧,我應該如何改變它來調用正確的對象? –