19

Refer to the code that @Yuri posted from here. How to stop a timer after certain number of times . If I wanted to stop it because of some condition and then restart it again. How would I go about doing it?

    private final static int DELAY = 10000;
    private final Handler handler = new Handler();
    private final Timer timer = new Timer();
    private final TimerTask task = new TimerTask() {
        private int counter = 0;
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
                }
            });
            if(++counter == 4) {
                timer.cancel();
            }

    //do some stuff in my app
   //restart the timer again

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer.schedule(task, DELAY, DELAY);

    }

Here's what I've tried , but it keeps crashing on me.

    final int DELAY = 10000;
        Timer timer;
        MyTask task;
        startManager Scanner;
        Handler handler;



        public class MyTask extends TimerTask {

            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        //do Stuff here
                        }
        });
    }
        public class startManager {

            public startManager() {
                handler = new Handler();
                timer = new Timer();
            }

            public void start() {

                timer.schedule(task, 0, DELAY);
            }

            public void cancel() {

                timer.cancel();
                timer.purge();

            }
        }

    }

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

Scanner = new startManager();
//do some stuff
 if (...)
Scanner.cancel()
//restart the timer and its task
Scanner=new startManager();
        }
Community
  • 1
  • 1
jimmyC
  • 563
  • 1
  • 6
  • 20
  • Does this answer your question? [Pausing/stopping and starting/resuming Java TimerTask continuously?](https://stackoverflow.com/questions/2098642/pausing-stopping-and-starting-resuming-java-timertask-continuously) – General Grievance Sep 10 '22 at 18:40

2 Answers2

2

FIgured it out, it was because I didn't initialize the task in startManager()

jimmyC
  • 563
  • 1
  • 6
  • 20
1

There appears to be no way to do this: http://docs.oracle.com/javaee/6/api/javax/ejb/Timer.html

You could likely cancel the timer, then create a new one.

Jonathan S. Fisher
  • 8,189
  • 6
  • 46
  • 84