[英]Android Gingerbread: Can't create handler inside thread that has not called Looper.prepare()
I have a code like this: 我有这样的代码:
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
The Timer should execute CheckMessageTask every 10 minutes. Timer应每10分钟执行一次CheckMessageTask。 The problem is that this error appears:
问题是出现此错误:
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 extends Asynctask and doesn't run UI code, so that is not the reason. CheckMessageTask扩展了Asynctask并且不运行UI代码,因此这不是原因。 The code works fine on Android Jelly Bean 4.1.2, but not on Android Gingerbread.
该代码在Android Jelly Bean 4.1.2上运行良好,但在Android Gingerbread上运行不正常。 How can I fix it?
我该如何解决?
您不能从UI线程执行Asynctask,这是使用Timer时的情况
Your timer task runs on a different thread. 您的计时器任务在不同的线程上运行。 You should load asynctask on the main ui thread
你应该在主ui线程上加载asynctask
Check the link below under the topic Threading Rules 检查主题线程规则下面的链接
http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/os/AsyncTask.html
The AsyncTask
class must be loaded on the UI thread
. 必须在
UI thread
上加载AsyncTask
类。 This is done automatically as of JELLY_BEAN
. 这是从
JELLY_BEAN
自动完成的。
So in Jelly bean it works fine. 所以在果冻豆中效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.