假设我想每 10 秒执行一次操作,并且不一定需要更新视图.
Let's say that I want to perform some action every 10 seconds and it doesn't necessarily need to update the view.
问题是:像这样使用 timer 和 timertask 是否更好(我的意思是更高效):
The question is: is it better (I mean more efficient and effective) to use timer with timertask like here:
final Handler handler = new Handler(); TimerTask timertask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { <some task> } }); } }; timer = new Timer(); timer.schedule(timertask, 0, 15000); }或者只是一个带有延迟的处理程序
or just a handler with postdelayed
final Handler handler = new Handler(); final Runnable r = new Runnable() { public void run() { <some task> } }; handler.postDelayed(r, 15000);此外,如果您能解释何时使用哪种方法以及为什么其中一种方法比另一种方法更有效(如果确实如此),我将不胜感激.
Also I would be grateful if you could explain when to use which approach and why one of them is more efficient than another (if it actually is).
推荐答案Handler 优于 TimerTask.
Handler is better than TimerTask.
Java TimerTask 和 Android Handler 都允许您在后台线程上安排延迟和重复的任务.然而,文献中绝大多数建议在 Android 中使用 Handler 而不是 TimerTask(参见 此处,此处a>,这里,此处,此处 和 此处).
The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).
一些已报告的 TimerTask 问题包括:
Some of reported problems with TimerTask include:
- 无法更新 UI 线程
- 内存泄漏
- 不可靠(并不总是有效)
- 长时间运行的任务可能会干扰下一个预定的事件
示例
我所见过的各种 Android 示例的最佳来源是 Codepath.这是重复任务的 Handler 示例.
The best source for all kinds of Android examples that I have seen is at Codepath. Here is a Handler example from there for a repeating task.
// 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);相关
- Handler vs Timer:固定周期执行和固定速率执行安卓开发
更多推荐
定时器任务或处理程序
发布评论