【问题标题】:Android : Progress Dialog not workingAndroid:进度对话框不起作用
【发布时间】:2014-08-31 14:22:58
【问题描述】:

当需要将数据上传到服务器时,我想显示一个 ProgressDialog。

我已经检查了这个问题Best way to show a loading/progress indicator? 最好的答案是

ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
// To dismiss the dialog
progress.dismiss();

当我试图在我的代码中实现它时,什么都没有显示!! 我在这里做错了什么?!

这是我的代码

private void UpdateData()
{

    ProgressDialog progress = new ProgressDialog(this);
    progress.setTitle("Loading");
    progress.setMessage("Wait while loading...");
    progress.show();

    try
    {
        UpdateWSTask updateWSTask = new UpdateWSTask();
        String Resp = updateWSTask.execute().get();

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    progress.dismiss();

}

【问题讨论】:

  • updateWSTask.execute().get() 必须是 updateWSTask.execute()get() 阻塞等待返回结果的 ui 线程。您希望任务是异步的。
  • 如何从 updateWSTask.execute() 传递参数?
  • 不要使用 get 只是用 execute 调用 asynctask
  • 您可以使用接口作为活动的回调。 stackoverflow.com/questions/16752073/…
  • @Raghunandan 但他在 task.execute().get() 之前显示对话框,所以它不应该是可见的吗?

标签: android multithreading show progressdialog


【解决方案1】:

显示ProgressDialogAsyncTask 的正确方法是在AsyncTaskonPreExecute() 方法上显示对话框并将其隐藏在onPostExecute() 方法上:

 private class SampleTask extends AsyncTask<Void, Integer, String> {

     ProgressDialog progress = new ProgressDialog(YourActivity.this);

     protected Long doInBackground(Void... urls) {

        // execute the background task
     }

     protected void onPreExecute(){

     // show the dialog
        progress.setTitle("Loading");
        progress.setMessage("Wait while loading...");
        progress.setIndeterminate(true);
        progress.show();
     }

     protected void onPostExecute(String result) {
         progress.hide();
     }
 }

两者:onPreExecute() 和 onPostExecute() 在主线程上运行,而 doInBackground() 顾名思义是在后台线程上执行。

编辑: 在您的 Activity 中,您想要调用 AsyncTask 只需执行它:

UpdateWSTask updateWSTask = new UpdateWSTask();
updateWSTask.execute();

【讨论】:

  • 这仍然不能解决发布代码中的所有问题。 get() 仍然会阻塞等待结果的ui线程
  • 我不建议调用 get()
  • 你可以建议 op 删除它。
  • @asmgx 你的execute(param)
  • 如果你想对结果做某事,你可以在 onPostExecute() 中执行它,或者你可以在你的活动中保留对结果的引用
【解决方案2】:

一个更好的主意是使用 AsyncTask 类来做到这一点。您可以在 preExecute 和 postExecute 方法中处理 UI 工作,并在 doInBackground 方法中完成主要工作。又好又干净!

看来您已经这样做了。将对话框代码移动到 asynctask 类。您只需要对上下文的引用,就可以为您的自定义 asynctask 类提供构造函数

【讨论】:

  • 移动AsyncTask里面的对话代码并不能说明他的问题
  • “在 AsyncTask 中移动代码”会得到相同的结果。 “您需要参考上下文”与他的问题无关。 task.execute().get() 方法是导致主线程等待后台线程结果的问题。
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多