Lester
Lester

Reputation: 283

Android Service calling AsyncTask

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);
 }

Upvotes: 3

Views: 6584

Answers (1)

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17115

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);
}

Upvotes: 1

Related Questions