Android: Restart Timer

Jan Knoblauch picture Jan Knoblauch · Feb 2, 2014 · Viewed 10.4k times · Source

I created a TimerTask with the following code:

    Screen_Timer_Task = new TimerTask() {

    @Override
    public void run() {

    runOnUiThread(new Runnable()
    {
            @Override
            public void run()
            {

                    // Do my stuff

            }
    });

    }

    };

Then, I start that TimerTask with that:

    Screen_Timer.scheduleAtFixedRate(Screen_Timer_Task, 1, 1);

This is working fine. But after calling

    Screen_Timer.cancel();

    Screen_Timer.purge();

it will not restart with

    Screen_Timer.scheduleAtFixedRate(Screen_Timer_Task, 1, 1);

The app is just crashing!!

Answer

Jan Knoblauch picture Jan Knoblauch · Feb 2, 2014
public void start_my_timer()
{

    Screen_Timer_Task = new TimerTask() {

        @Override
        public void run() {


                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                                // Do my stuff
                    }
                });

        }

    };

    Screen_Timer.schedule(Screen_Timer_Task, 1, 1);

}