0

当我在按钮的单击方法中使用以下代码创建进度条时。但是单击按钮后需要 2-3 秒才能显示进度条。如何减少启动进度条的延迟。

 public void getProgressBar() {

    progressBar = new ProgressDialog(this);
    progressBar.setCancelable(true);
    progressBar.setMessage("Loading...");
    progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressBar.show();
    progressBarStatus = 0;

    new Thread(new Runnable() {
        public void run() {
            while (progressBarStatus < 100) {

                progressBarStatus = doSomeTasks();////I am loading service 
                progressBarHandler.post(new Runnable() {
                    public void run() {
                        progressBar.setProgress(progressBarStatus);
                    }
                });
            }

                if (progressBarStatus >= 100 ) {

                    progressBar.dismiss();
                    startActivity(new Intent(getApplicationContext(),
                            StatisticDisplay.class));

            }
        }
    }).start();
}
4

2 回答 2

0

请改用AsyncTask。链接中的示例代码很好地介绍了如何执行此操作。本质上,您在 doInBackground() 中完成工作,使用 onProgressUpdate() 发布您的进度并在 onPostExecute() 中开始您的活动。

于 2012-04-09T11:49:37.777 回答
0
 public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {

  int myProgress;

  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   myProgress = 0;
  }

  @Override
  protected Void doInBackground(Void... params) {
   // TODO Auto-generated method stub
   while(myProgress<100){
    myProgress++;
    publishProgress(myProgress);
       SystemClock.sleep(100);
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   // TODO Auto-generated method stub
   progressBar.setProgress(values[0]);
  }
}
于 2012-04-09T11:58:27.807 回答