如何使用异步任务多次暂停程序

时间:2012-06-25 20:10:11

标签: android multithreading asynchronous

我知道标题有点令人困惑,我的问题是:我想使用sleep(ms)多次(暂停)我的程序“暂停”并更改用户按下的几个按钮。我知道UI的更改只能在主线程中进行,所以我想知道如何将此代码转换为异步任务。我还记得在哪里读过Async任务只能调用一次?如果是这样,我可以研究哪些其他解决方案?

View.OnClickListener SimulateButtonHandler = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        for(int j=0;j<169;j++) //169 buttons to click
        {
            if(ClickedPoints[j]!=null) //how I keep track of which buttons has clicked
            {       //clear button color
                Drawable d2 = ClickedPoints[j].getBackground();  
                ClickedPoints[j].invalidateDrawable(d2);  
                d2.clearColorFilter();
            }

        }

        Timer timer = new Timer();

        for(int i=0;i<169;i++)
        {
            if(ClickedPoints[i]!=null)
            {       //change the color after some time
                Simulate(timer, i);
                //clear color again
                Drawable d2 = ClickedPoints[i].getBackground();  
                ClickedPoints[i].invalidateDrawable(d2);  
                d2.clearColorFilter();

            }

        }
}   
};

public void Simulate(Timer timer, final int index)
{
    timer.schedule(new TimerTask()
    {
        public void run() {
            Sim(index);
        }

    }, 1000); //delay for some amount of time, then rehighlight the button
}

private void Sim(int i)
{
    Drawable d1 = ClickedPoints[i].getBackground();  
    PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);  
    d1.setColorFilter(filter);
}

1 个答案:

答案 0 :(得分:0)

最好使用Thread运行后台工作(并暂停)和Handler来访问UI线程。

使用带线程的处理程序时,这是一个很好的tutorial