Android Playing sound in AsyncTask when ToggleButton is checked

↘锁芯ラ 提交于 2019-12-12 02:06:24

问题


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 it crashes why? What should I do to make it loop sound in 1 second intervals when toggle button is checked?

Solved by AlexanderFox

My current java code:

    final ToggleButton metronomepp = (ToggleButton) findViewById (R.id.metronomepp);
    metronomepp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i("Metronome", "InWhile");

                if(isChecked) {
                    currentTask = new TimerTask() {
                        @Override
                        public void run() {
                            if (metronome.isPlaying()) { metronome.pause(); }
                            metronome.seekTo(0);
                            metronome.start();
                        }
                    };
                    myTimer.schedule(currentTask, 0, 1000); 
                } else {
                    currentTask.cancel();
               }   
        }
    });

I am now having problem with changing time to wait. I have double variable timetw and chnaged 1000 to timetw with cast to long but app crashes when I check toggle button if I had changed time based on selection in app.


回答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):

private TimerTask currentTask;

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(isChecked) {
        currentTask = new TimerTask() {
            @Override
            public void run() {
                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();
    }
}


来源:https://stackoverflow.com/questions/15427797/android-playing-sound-in-asynctask-when-togglebutton-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!