3

I am having problems when trying to call the constructor of the asynctask inside a service.

I got this error

Can't create handler inside thread that has not called Looper.prepare().

Should I call the AsyncTask inside a UIThread?

Strangely, It is working in Jellybean but crashing in ICS.

 @Override
 public void onCreate(){
    super.onCreate();
    WebRequest wr = new WebRequest(this.serviceURL, this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        wr.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, processType, newMap);
    else
        wr.execute(processType, newMap);
 }
StarPinkER
  • 14,081
  • 7
  • 55
  • 81
Lester
  • 283
  • 7
  • 14

1 Answers1

1

From that exception it seems you are calling it not from UI thread. AsyncTask can only be called from the UI thread. As far as I remember, IntentService does not run on ui thread and you are extending it (?). So you don't need to use AsyncTask. But if you really want, you can do things from UI thread in the Handler.

private static final Handler handler = new Handler();

private final Runnable action = new Runnable() {
    @Override
    public void run() {
        WebRequest wr = new WebRequest(this.serviceURL, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            wr.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, processType, newMap);
        else
            wr.execute(processType, newMap);
    }
};

@Override
public void onCreate(){
    super.onCreate();
    handler.post(action);
}
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99
  • 2
    Thanks. I also learned that Async tasks automatically run in the UI thread for Jellybean, but for lower versions you'll have to create new runnable. – Lester May 06 '13 at 03:34
  • I also found that static final Handler handler = new Handler(); fails in non-context classes, so you have to create a static Handler and initialize it in constructor, like if (handler == null) handler = new Handler(context.getMainLooper()); – Yaroslav Mytkalyk May 06 '13 at 10:21