thej thej - 3 months ago 15
Android Question

reduce delay in display progress bar

As I created a Progress bar using below code in a on click method of button. but after clicking button it takes 2-3 seconds to display progress bar.how to reduce that delay to start progress bar.

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();
}

Answer
 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]);
  }
}
Comments