我有这样的代码:
final Context context = this;
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
@Override
public void run()
{
new CheckMessageTask(context).execute(); //ERROR
}
}, 2500, 10 * 60 * 1000); //Every 10 Minutes
Timer 应该每 10 分钟执行一次 CheckMessageTask。问题是出现了这个错误:
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
java.lang.ExceptionInInitializerError
at -package-CheckMessageService$1.run(CheckMessageService.java:138)
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()
at android.os.Handler.<init>(Handler.java:121)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
... 2 more
CheckMessageTask 扩展了 Asynctask 并且不运行 UI 代码,所以这不是原因。该代码适用于 Android Jelly Bean 4.1.2,但不适用于 Android Gingerbread。我该如何解决?