在Android的AsyncTask的声音播放时切换按钮被选中 [英] Android Playing sound in AsyncTask when ToggleButton is checked

查看:136
本文介绍了在Android的AsyncTask的声音播放时切换按钮被选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置会以1秒的间隔进行循环切换时,按钮被选中声音。我试图让AsyncTask的为后来当我打开这个活动它崩溃了,为什么?我应该怎么做,使之循环声音间隔1秒时拨动按钮被选中?

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?

由AlexanderFox解决

Solved by AlexanderFox

我当前的Java code:

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

我现在有不断变化的时间等待问题。我有双重可变timetw和chnaged 1000,强制转换为长,但应用程序崩溃到timetw当我检查切换按钮,如果我基于应用的选择改变了时间。

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.

推荐答案

我想用无限的,而循环是非常糟糕的主意。更好地利用<一个href=\"http://developer.android.com/reference/java/util/Timer.html#schedule%28java.util.TimerTask,%20long,%20long%29\"相对=nofollow>日程表 Timer类的方法来达到这一点。当你不再需要此任务可以重复刚刚所说的取消计时器的方法。

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.

例如(修正):

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

这篇关于在Android的AsyncTask的声音播放时切换按钮被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆