【问题标题】:Android Service calling AsyncTaskAndroid 服务调用 AsyncTask
【发布时间】:2013-04-19 19:19:19
【问题描述】:

尝试在服务中调用异步任务的构造函数时遇到问题。

我收到了这个错误

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

【问题讨论】:

  • 你能提供更多代码吗?看来您的代码是正确的。

标签: java android multithreading android-asynctask android-service


【解决方案1】:

从该异常看来,您不是从 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);
}

【讨论】:

  • 谢谢。我还了解到 Async 任务会自动在 Jellybean 的 UI 线程中运行,但对于较低版本,您必须创建新的可运行对象。
  • 我还发现 static final Handler handler = new Handler();在非上下文类中失败,因此您必须创建一个静态处理程序并在构造函数中对其进行初始化,例如 if (handler == null) handler = new Handler(context.getMainLooper());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
相关资源
最近更新 更多