Reputation: 1027
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. 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. The code works fine on Android Jelly Bean 4.1.2, but not on Android Gingerbread. How can I fix it?
Upvotes: 0
Views: 1017
Reputation: 133560
Your timer task runs on a different thread. You should load asynctask on the main ui thread
Check the link below under the topic Threading Rules
http://developer.android.com/reference/android/os/AsyncTask.html
The AsyncTask
class must be loaded on the UI thread
. This is done automatically as of JELLY_BEAN
.
So in Jelly bean it works fine.
Upvotes: 2
Reputation: 24720
you cannot execute Asynctask from not a UI thread which is a case when using a Timer
Upvotes: 1