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開發