定时器任务或处理程序 [英] Timertask or Handler

查看:24
本文介绍了定时器任务或处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想每 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);

相关

这篇关于定时器任务或处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆