ProgressDialog 不显示进度

ProgressDialog doesn't show a progress

我使用 ProgressDialog 用法的简单示例。此代码的作者确信他的代码是正确的并且运行良好。

    ProgressDialog barProgressDialog;
      Handler updateBarHandler;

    public void launchBarDialog() {
    barProgressDialog = new ProgressDialog(getActivity());

    barProgressDialog.setTitle("Downloading Image ...");
    barProgressDialog.setMessage("Download in progress ...");
    barProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    barProgressDialog.setProgress(0);
    barProgressDialog.setMax(20);
    barProgressDialog.show();

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          // Here you should write your time consuming task...
          while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
            Thread.sleep(2000);
            updateBarHandler.post(new Runnable() {
              public void run() {
                barProgressDialog.incrementProgressBy(2);
              }
            });
            if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
              barProgressDialog.dismiss();
            }
          }
        } catch (Exception e) {
        }
      }
    }).start();
  }

但是当我在我的项目中 运行 这段代码时,我看到 ProgressDialog 始终显示 0 值作为进度。我做错了什么?

试试下面的代码:

private ProgressDialog barProgressDialog;

public void launchBarDialog() {
        barProgressDialog = new ProgressDialog(this);

        barProgressDialog.setTitle("Downloading Image ...");
        barProgressDialog.setMessage("Download in progress ...");
        barProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        barProgressDialog.setProgress(0);
        barProgressDialog.setMax(20);
        barProgressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Here you should write your time consuming task...
                    while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
                        Thread.sleep(2000);
                        barProgressDialog.incrementProgressBy(2);

                        if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
                            barProgressDialog.dismiss();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Log.d("", BuildConfig.VERSION_NAME);
    }