简体   繁体   English

Android服务调用AsyncTask

[英]Android Service calling AsyncTask

I am having problems when trying to call the constructor of the asynctask inside a service. 尝试在服务中调用asynctask的构造函数时遇到问题。

I got this error 我收到了这个错误

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

Should I call the AsyncTask inside a UIThread? 我应该在UIThread中调用AsyncTask吗?

Strangely, It is working in Jellybean but crashing in ICS. 奇怪的是,它在Jellybean工作但在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);
 }

From that exception it seems you are calling it not from UI thread. 从该异常看来,您不是从UI线程调用它。 AsyncTask can only be called from the UI thread. 只能从UI线程调用AsyncTask。 As far as I remember, IntentService does not run on ui thread and you are extending it (?). 据我所知,IntentService不会在ui线程上运行而你正在扩展它(?)。 So you don't need to use AsyncTask. 所以你不需要使用AsyncTask。 But if you really want, you can do things from UI thread in the Handler. 但是如果你真的想要,你可以在Handler的UI线程中做一些事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM