我在按钮的点击方法中使用下面的代码创建了一个进度条。但点击按钮后,显示进度条需要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();
}
答案 0 :(得分:0)
请改用AsyncTask。链接中的示例代码很好地介绍了如何执行此操作。本质上,您在doInBackground()中完成工作,使用onProgressUpdate()发布您的进度,并在onPostExecute()中启动您的活动。
答案 1 :(得分: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]);
}
}