ProgressDialog 不显示

ProgressDialog not displaying

我有一个进度对话框,我希望它在我的方法执行完毕后显示并关闭。现在,我有这个:

progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("Downloading...");
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            DownloadMethod(s);
                            progressDialog.dismiss();
                        }catch (Exception e){
                            Toast.makeText(prefs.this, "We can't reach the data...Try again", Toast.LENGTH_SHORT).show();
                        }

                    }
                }).start();

我的方法 DownloadMethod 已执行但从未显示对话框。

实际上,它必须通过 progressDialog.dismiss(); 调用抛出异常,因为您不能从工作线程更新 UI,而是使用 AsyncTask

例如将参数传递给构造函数

 private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
    TypeOf_S s;

     public DownloadFilesTask(TypeOf_S s){
        this.s = s;
     }

     @Override
     protected Void doInBackground(Void... obj) {
         DownloadMethod(s);
         return null;
     }

     @Override
     protected void onPostExecute(Void result) {
         progressDialog.dismiss();
     }
 }

并称​​其为 new DownloadFilesTask(s).execute();

或使用通用参数

private class DownloadFilesTask extends AsyncTask<TypeOf_S, Void, Void> {

     @Override
     protected Void doInBackground(TypeOf_S... obj) {
         DownloadMethod(obj[0]);
         return null;
     }

     @Override
     protected void onPostExecute(Void result) {
         progressDialog.dismiss();
     }
 }

并称​​其为 new DownloadFilesTask().execute(s);

progressDialog.dismiss(); 抛出异常,因此将您的代码移动到 runOnUiThread() 方法中,如下所示:

 runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       progressDialog.dismiss();
                    }
                });

根据 Pavneet 的建议,您可以按如下方式使用异步任务,其中 AsyncTask<String, void, String> 对应于输入类型进度值,最后一个是您感兴趣的结果值,因此请相应地提供数据类型。

    private class DownloadFilesTask extends AsyncTask<String, void, String> {
     protected String doInBackground(String... urls) {
         //here do the actual downloading instead of calling the DownloadMethod(s)
     }

     protected void onPreExecute() {
         //here show the dialog
         progressDialog.show();
     }

     protected void onPostExecute(String result) {
         //here hide the dialog
         progressDialog.dismiss();
     }
 }

在你调用下载函数的地方你就调用这个

progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
new DownloadFilesTask().execute(s);
//here s is assumed to be string type you can give anything