Handler优于Handler。
Java Handler和Android Handler都允许您在后台线程上安排延迟和重复的任务。 但是,绝大多数文献建议在Android中使用Handler而不是2307674266333338147(参见此处,此处,此处,此处,此处和此处)。
一些报告的TimerTask问题包括:
无法更新UI线程
内存泄漏
不可靠(并不总是有效)
长时间运行的任务可能会干扰下一个预定的事件
例
我见过的各种Android示例的最佳来源是Codepath。 这是一个重复任务的Handler示例。
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
有关
处理程序与计时器:固定期执行和固定速率执行android开发