【发布时间】: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