【发布时间】:2012-03-05 04:07:47
【问题描述】:
我有这似乎是一项非常繁琐的任务,即重新安排 Timer 和 TimerTask 以使我的服务/正在进行的进程能够在不同时间执行...我尝试搜索许多论坛,包括 this example,这似乎已经奏效对于这个人,但是当我在我的服务中尝试相同的代码时,我收到以下错误:
03-04 14:21:41.204:E/AndroidRuntime(336):致命异常:Timer-0
03-04 14:21:41.204: E/AndroidRuntime(336): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
有谁知道这个错误是什么意思,有什么可能的解决方案?根据我在网上研究的有关此错误的信息:它通常发生在我尝试在非 UI 线程上进行 UI 更改时...在我的情况下,我所做的只是发送通知,然后调用 reScheduleTimer 函数,如该示例中...
任何意见表示赞赏...
编辑: 这是它爆炸的代码:
public void reScheduleTimer(long duration) {
Log.v(TAG, "Inside reScheduleTimer");
timer.cancel();
timer = new Timer("profileSwitcherTimer", true);
timerTask = new MyTimerTask(); <----
timer.schedule(timerTask, duration);
}
这是 MyTimerTask 类:
public class MyTimerTask extends TimerTask{
private Handler updateUI = new Handler(){
public void dispatchMessage(Message msg) {
Toast.makeText(getApplicationContext(), "Timer Ran", Toast.LENGTH_LONG).show();
}
}
public void run() {
....code that i want execute
showNotification();
reScheduleTimer(60000);
}
}
【问题讨论】:
-
你能贴出抛出异常的代码块吗?如果我们能看到您已经写的内容会更有帮助。
-
@Robert:使用我正在使用的代码的 sn-ps 编辑原始帖子...