【发布时间】:2013-10-02 12:58:04
【问题描述】:
在 Android 4.3 中,此代码有效。 但在 android
10-02 00:10:55.265: ERROR/AndroidRuntime(356): FATAL EXCEPTION: Timer-0
java.lang.ExceptionInInitializerError
at ru.cl.radio.MyActivity$1$1.run(MyActivity.java:129)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
代码:
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask () {
@Override
public void run () {
if(isOnline()){
DownloadWebPageTask task = new DownloadWebPageTask(); // **129 line!!!**
task.execute(new String[] { "http://.../index.php" });
} else{
runOnUiThread(successRunnable);
}
}
};
timer.schedule (hourlyTask, 0l, 1000*30);
我希望看到 此代码每 30 秒重复一次
if(isOnline()){
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://...index.php" });
} else {
runOnUiThread(successRunnable);
}
【问题讨论】:
-
看看这个答案中的处理程序示例代码:stackoverflow.com/a/16886486/273628
-
task.execute 应该在您希望 onPostExecute 运行的线程上运行,并且该线程需要一个循环器。通常是ui线程。