【问题标题】:How can I implement a Timer/TimerTask that executes an AsyncTask? (Android)如何实现执行 AsyncTask 的 Timer/TimerTask? (安卓)
【发布时间】:2011-09-01 20:33:00
【问题描述】:

我正在尝试在指定时间(即每隔几秒,尽管此速率可能会在运行时发生变化)异步并重复地执行一项任务(即从文本文件加载数据)。

我做了一些研究并决定这将需要一个 AsyncTask 或一个单独的线程。为简单起见,我决定使用 AsyncTask。

我现在需要根据重复的计时器计划来执行这个 AsyncTask。我相信我必须使用 Timer 和 TimerTask。

下面的代码是我想要实现的简单形式。当我尝试使用 Android 模拟器(通过 Eclipse IDE)运行此代码时,我收到以下消息:“抱歉!应用程序已意外停止。请重试。”

我想知道问题出在哪里以及如何解决。谢谢!

public class Sample extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SimpleTimerTask myTimerTask = new SimpleTimerTask(); 

    long delay = 0;
    long period = 5000;

    Timer myTimer = new Timer();
    myTimer.schedule(myTimerTask, delay, period);
}


private class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        return null;
    }   
}


private class SimpleTimerTask extends TimerTask {
    public void run() {
        new SimpleAsyncTask().execute();
    }       
}

}

编辑:这里是似乎相关的 LogCat 消息

致命异常:Timer-0

java.lang.ExceptionInInitializerError

在……

原因:java.lang.RuntimeException: Can't create handler inside the thread that has not called Looper.prepare()

在……

【问题讨论】:

  • logcat 中的日志是怎么说的?你可能会在那里找到一个堆栈跟踪,它表明你的问题。
  • @Kaj - 这是一个非常有用的评论(至少对于像我这样的初学者 Android 开发人员)。我什至不知道 LogCat 是什么,但现在我看到了它在调试/错误跟踪方面的价值。

标签: android multithreading timer android-asynctask timertask


【解决方案1】:

你让这种方式变得比它需要的更难。 TimerTask 已经在它自己的线程上运行,所以你不需要使用AsyncTask,只需将要运行的代码放在TimerTask.run() 方法中即可。

【讨论】:

  • 有趣。我绝对更喜欢这个解决方案,因为它更简单。我只需要弄清楚我现在如何从 TimerTask 线程更新 UI ......有什么想法吗?感谢您的帮助!
  • 您可以传入Handler 以将Messages 发送到UI 线程。
【解决方案2】:

如果您想从 OnPostExecute 方法更新 UI,则将 timertask 与 asynctask 一起使用会受到严重限制。计时器在单独的线程中运行,因此您必须找到一种从主线程启动异步任务的方法。

【讨论】: