Question

In my app I use TimerTask to repeat an action every x seconds, but now I want to stop the TimerTask with a button and run it again by pressing another. Here is what I have so far:

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



                }
            });
        }
    }

naturally when I click stop TextView and then the Start TextView for restart TimerTask, it give me

java.lang.IllegalStateException: Timer was canceled 
Était-ce utile?

La solution

In Android, threads and timers are not reusable, so the thread in your timertask can't be reused. Every time you want to re-launch your TimerTask, you need to instantiate a new one.

So add these lines

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

before this one

Tempogatto.schedule(timerTempogatto, 0, 20000);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top