0

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?

Enes Sadık Özbek
  • 993
  • 10
  • 17

2 Answers2

2

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.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

you cannot execute Asynctask from not a UI thread which is a case when using a Timer

pskink
  • 23,874
  • 6
  • 66
  • 77
  • because in 4.1.2 this done automatically. The `AsyncTask` class must be loaded on the UI thread. This is `done automatically` as of `JELLY_BEAN`. – Raghunandan Jun 11 '13 at 17:07
  • have no idea, see http://developer.android.com/reference/android/os/AsyncTask.html section "Threading rules" – pskink Jun 11 '13 at 17:10
  • @Trojaner can you explain why you want a timer? i think you have to rethink your appraoxh – Raghunandan Jun 11 '13 at 17:13
  • The code is executed by a service, so there is no UI Thread. @Raghunandan how should i do it? – Enes Sadık Özbek Jun 11 '13 at 17:15
  • @Trojaner i suggest you rethink your design. service runs in background. in service you have a timer and you load asynctask inside the timer. you have to change your approach. do you need parallel execution? – Raghunandan Jun 11 '13 at 17:16