AnZyuZya
AnZyuZya

Reputation: 201

Show ProgressDialog ONLY when process is long

I'm wondering how do you show ProgressDialog only in that case when process takes long time?

In my case program works with internet and if phone is connected via WiFi so there's no need in progressDialogs since it would flash for half a sec. And vise versa when internet is slow its needed to show them.

How can I do such:

if (process takes > 1 sec) -> ProgressDialog.show(...)

Upvotes: 0

Views: 560

Answers (1)

Ben
Ben

Reputation: 1295

It depends how you are running your process. In the case of AsyncTask just start a timer when you start the async task. Then in your doInBackground you can query for the elapsed time and call publishProgress if the time is greater then a few seconds. Then in onProgressUpdate publish your dialog.

If your not using async task you'll have to adjust for whatever method your following. Generally capture the start time, poll to query the current time, when you surpass your time threshold display progress dialog.

 private class MyTask extends AsyncTask<FOO, FOO, FOO> {
 protected Long doInBackground(FOO... foo) {
     //Do normal operation
     long elapsedTime = System.currentTimeMillis();
     boolean showDialog = false;
     if (elapsedTime - startTime > TIME_THRESHOLD) {
        showDialog = true;
        publishProgress(0);
     }

     while( !showDialog ) {
        elapsedTime = System.currentTimeMillis();
        if (elapsedTime - startTime > TIME_THRESHOLD) {
          showDialog = true;
          publishProgress(0);
        }
     }
 }

 protected void onProgressUpdate(Integer... progress) {
     //Show dialog
 }

 protected void onPostExecute(Long result) {
     //Do whatever
 }
}
startTime = system.currentTimeMillis();
new MyTask().execute();

This is a pretty rough implementations, the time checking can be improved but should give a rough idea of how to make it work. startTime in this case would be a class variable in your containing class.

Upvotes: 1

Related Questions