TimerTask取消/重启

时间:2014-03-10 16:43:34

标签: java android timertask

在我的应用中,我使用TimerTask每x秒重复一次操作,但现在我想用一个按钮停止TimerTask并按另一个按钮再次运行它。以下是我到目前为止的情况:

public class MainActivity extends Activity {

Timer Tempogatto = new Timer();
timerTempogatto timerTempogatto = new timerTempogatto();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


final TextView  start = (TextView)findViewById(R.id.start);
start.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){

    Tempogatto.schedule(timerTempogatto, 0, 20000);         

}

    return true;
}

});  

final TextView  stop = (TextView)findViewById(R.id.stop);
stop.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){

    Tempogatto.cancel                       

 }  
return true;
}

});  






(.....)

    private class timerTempogatto extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    //code i want to repeat every 20 second



                }
            });
        }
    }

当我点击停止TextView,然后点击开始TextView重新启动TimerTask时,它自然会给我

java.lang.IllegalStateException: Timer was canceled 

1 个答案:

答案 0 :(得分:0)

在Android中,线程和计时器不可重用,因此您的timertask中的线程无法重用。每次要重新启动TimerTask时,都需要实例化一个新的。

所以添加这些行

Tempogatto = new Timer();
timerTempogatto = new timerTempogatto();

之前

Tempogatto.schedule(timerTempogatto, 0, 20000);