简体   繁体   中英

Java Timer in android

How can this be done in android?

public final Timer timer = new Timer(10, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {  
          // Do task here       
        }
    });

I need to be able to call timer.start(); from the Activity that timer is in.

In most cases it is much better to use a Handler instead of Timer. Handler is capable of sending delayed messages. Benefits of using Handler are:

  • it runs on the main (UI) thread -> can access Views (unlike the Timer, which cannot dircetly access Views)
  • You can remove pending delayed messages if you want
  • Less code

Example:

class MyActivity extends Activity {

    private static final int DISPLAY_DATA = 1;
    // this handler will receive a delayed message
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // Do task here
            if (msg.what == DISPLAY_DATA) displayData();
        }
 };

 @Override
 void onCreate(Bundle b) {
     //this will post a message to the mHandler, which mHandler will get
     //after 5 seconds
     mHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 5000);
 }
}

Try something like this:

// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {

    @Override
    public void run() {
        // ...
    }

};

// new timer
Timer timer = new Timer();

// schedule timer
timer.schedule(myTimerTask, delayInMs);

If you want task to be done in activity's main thread, modify it like this:

// get a handler (call from main thread)
final Handler handler = new Handler();

// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
    @Override
    public void run() {
        // post a runnable to the handler
        handler.post(new Runnable() {
            @Override
            public void run() {
                // ...
            }
        });
    }
};

// new timer
Timer timer = new Timer();

// schedule timer
timer.schedule(myTimerTask, delayInMs);

Android也有一个很好的CountDownTimer

I have answered this in another question.

I would avoid the TimerTask, if you fire a lot of them off, they are not only difficult to manage but bad for performance.

I would recommend a Handler for pretty much any Time based task these days.

See Timer application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM