我在尝试调用服务内的异步任务的构造函数时遇到问题。
我遇到了这个错误
Can't create handler inside thread that has not called Looper.prepare().
我应该在 UIThread 中调用 AsyncTask 吗?
奇怪的是,它在 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);
}
最佳答案
从那个异常来看,您似乎不是从 UI 线程调用它。 AsyncTask 只能从 UI 线程调用。 据我所知,IntentService 不在 ui 线程上运行,您正在扩展它(?)。所以你不需要使用 AsyncTask。但如果您真的想要,您可以在 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);
}
关于java - Android 服务调用 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16101947/