Android:第一次未显示进度对话框(使用Thread或AsyncTask进行longDuration操作)

时间:2012-11-07 15:23:01

标签: android multithreading android-asynctask progressdialog

我的应用程序中存在问题,在AsyncTask中有进度对话框: 我的AsyncTask正在doInBackGround()从互联网上做一些geting数据,我在onPreExecute()开始进度对话,在onPostExecute()完成对话。

单击Button时执行此asyncTask。第一次单击此按钮(发生长时间操作)时,不显示进度对话框。但下一次进度对话框显示正常。

第一次运行AsyncTask,进度对话框未显示的问题是什么?

这是onClick方法:

public void onClickFind(View view){
 new Task_Search().execute();
}

这是任务Task_Search

private class Task_Search extends AsyncTask<Void, Void, Void> {

 @SuppressWarnings("deprecation")
 protected void onPreExecute() {
  showDialog(DIALOG_TASKING);
 }

 protected Void doInBackground(Void... unused) {
  //some geting of web content here
 }

 @SuppressWarnings("deprecation")
 protected void onPostExecute(Void unused) {
  dismissDialog(DIALOG_TASKING);
 }
}

MainActivity中定义的进度对话框:

@SuppressWarnings("deprecation")
@Override
protected Dialog onCreateDialog(int id) {
 switch (id) {
 case DIALOG_TASKING:
  mSearchDialog = new ProgressDialog(this);
  mSearchDialog.setMessage("Searching for field number..");
  mSearchDialog.setCancelable(true);
  return mSearchDialog;
  }
 return super.onCreateDialog(id);
}

在使用AsyncTask之前,我使用单独的线程代替下载数据:在onClick中,我首先开始progressDialog然后开始线程,当线程完成时progressDialog被停止, 行为是一样的: 第一次单击按钮对话框未显示,下一次显示。

任何可以提供帮助的人?

3 个答案:

答案 0 :(得分:0)

我看不到你在对话框上调用show()。

替换

@SuppressWarnings("deprecation")
protected void onPreExecute() {
    showDialog(DIALOG_TASKING);
}

@SuppressWarnings("deprecation")
protected void onPreExecute() {
    showDialog(DIALOG_TASKING).show();
}

答案 1 :(得分:0)

不要在showExalcute()上调用showDialog insode。 AsyncTask提供了publishProgress()方法,可以从doInBackground()调用它来在UI线程上发布更新。

答案 2 :(得分:0)

好, 我在MainActivity中创建了自己的方法:

public void showProgressDialog() {
 if (mProgressDialog == null) {
  mProgressDialog = new ProgressDialog(this);
  mProgressDialog.setMessage("Searching for field number..");
  mProgressDialog.show();
  return;
 }else{
  mProgressDialog.setMessage("Searching for field number..");
  mProgressDialog.show();
  return;
 }

}

也:

public void closeProgressDialog() {
 if (mProgressDialog != null) {
  mProgressDialog.dismiss();
 }
 return;
}

我更改了AsyncTask:

private class Task_Search extends AsyncTask<Void, Void, Void> {
 protected void onPreExecute() {
  // showDialog(DIALOG_TASKING);
  showProgressDialog();
 }

 protected Void doInBackground(Void... unused) {
 //Some long duration stuff here
 }

 protected void onPostExecute(Void unused) {
  //dismissDialog(DIALOG_TASKING);
  closeProgressDialog();
 }
}

mProgressDialog是MainActivity的私人成员

private ProgressDialog mProgressDialog;

情况相同:点击onClick按钮:第一次进行ProgressDialog卡住,下一次它完美无缺