为什么我不能在AsyncTask的doInBackground方法中运行ProgressDialog?

时间:2011-11-15 22:02:55

标签: android android-asynctask progressdialog

我无法在AsyncTask的ProgressDialog方法中运行doInBackground。它给了我以下错误:

  

错误/ AndroidRuntime(12986):引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序

错误在代码中的这一行:

final ProgressDialog dialog = ProgressDialog.show(GalleryView.this, "Refresh", "Loading... please wait", true);

任何帮助都非常感激。

4 个答案:

答案 0 :(得分:3)

您可以在onPreExecute方法中显示progressdialog,并在onPostExecute方法中将其关闭。这两个方法在UI线程中运行。 doInBackGround方法在另一个线程中运行。

另一种可能性是在启动AsyncTask之前只显示progressdialog。我个人喜欢使用onPreExecute和onPostExecute的选项。然后,progressdialog很好地链接到AsyncTask。

答案 1 :(得分:1)

由于doinbackground不在ui线程上运行,因此无法创建UI元素。您应该在执行AsyncTask之前创建进度对话框。

答案 2 :(得分:1)

AsyncTask构造是关于分离背景和UI线程操作。在doInBrackground范围内,您不在UI线程中,因此您根本无法执行与UI相关的逻辑。正确的地方是在UI线程上运行的方法。我猜你的具体情况是onPreExecute

答案 3 :(得分:1)

ProgressDialog是UI代码,因此它必须发生在事件队列中。 AsyncTask运行事件队列。你可以这样做一个进度对话框:

ProgressBar progressBar = activity.findViewById(progressBarID);
progressBar.setIndeterminate(true)
progressBar.setVisibility(View.VISIBLE);
AsyncTask<Void, Void, Void> aTask = new AsyncTask<Void, Void, Void>(){
 @Override
  protected Void doInBackground(Void... arg0) {
    //Do your operations here
   return null;
 }

 @Override
 protected void onPostExecute(Void result) {
    progressBar.setVisibility(View.GONE);
        //Wrap up anything here, like closing the popup.
 }
};
aTask.execute((Void)null);