Skip to content Skip to sidebar Skip to footer

Android Playing Sound In Asynctask When Togglebutton Is Checked

I am trying to set a sound that is going to be looped in intervals of 1 second when toggle button is checked. I tried to make asynctask for that but then when I open this activity

Solution 1:

I think using infinite "while" loop is very bad idea. Better use schedule method of Timer class to reach that. When you no longer need this task to be repeated just call "cancel" method of Timer.

For example (corrected):

privateTimerTask currentTask;

@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(isChecked) {
        currentTask = newTimerTask() {
            @Overridepublicvoidrun() {
                if (metronome.isPlaying()) { metronome.pause(); }
                metronome.seekTo(0);
                metronome.start();
            }
        };
        myTimer.schedule(currentTask, 0, 1000); //in this line we tell to repeat sound every second without start delay
    } else {
        currentTask.cancel();
    }
}

Post a Comment for "Android Playing Sound In Asynctask When Togglebutton Is Checked"