简体   繁体   English

android中的Java Timer

[英]Java Timer in android

How can this be done in android? 怎么能在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(); 我需要能够调用timer.start(); from the Activity that timer is in. 来自计时器所在的活动。

In most cases it is much better to use a Handler instead of Timer. 在大多数情况下,使用Handler而不是Timer更好。 Handler is capable of sending delayed messages. 处理程序能够发送延迟消息。 Benefits of using Handler are: 使用Handler的好处是:

  • it runs on the main (UI) thread -> can access Views (unlike the Timer, which cannot dircetly access Views) 它运行在主(UI)线程上 - >可以访问视图(不像Timer,它不能直接访问视图)
  • 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: 如果您希望在activity的主线程中完成任务,请像下面这样修改它:

// 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. 我会避免使用TimerTask,如果你关掉它们很多,它们不仅难以管理而且对性能有害。

I would recommend a Handler for pretty much any Time based task these days. 这些天我会推荐一款Handler用于几乎任何基于时间的任务。

See Timer application 请参阅定时器应用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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