Nongdan Xitrum
Nongdan Xitrum

Reputation: 11

How to use Java Timer in Android?

My program with Timer was working in Java but not working in Android. Android did not accept ActionListener, ActionEvent or timer.start(), timer.stop(). What should I do? Thanks a lot for any help!

   private Timer timer;

    timer = new Timer(2 * 1000, new ActionListener(){
    public void actionPerformed(ActionEvent e) {

            if(condition == true) {
            // do my job when it's true
                                   }
            else{
            timer.stop(); //stop it
                 }
                                                 }
            });
            timer.setRepeats(true);//auto restarts the timer after it triggers

Upvotes: 0

Views: 255

Answers (1)

gknicker
gknicker

Reputation: 5568

You must use the java.util.Timer class instead of the javax.swing.Timer class you were using before.

Therefore you must construct the timer with a java.util.TimerTask instead of an ActionListener.

Also you can't repeatedly stop and start this kind of timer. You can only cancel() it, after which it cannot be reused, so you must create a new Timer for each time you want to start one.

Upvotes: 1

Related Questions