lundi 16 mai 2016

Android mediaplayer does not stop on checkbox

I built a small app which basically vibrates and plays an mp3 file on checking a checkbox, but somehow the music won't stop after unchecking the checkbox:

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();
                    }
                }
            }
        );
    }
}




Aucun commentaire:

Enregistrer un commentaire