Gaurav
Gaurav

Reputation: 41

How to wait for a specific amount of time between iterations in a for loop in Android/Java?

I'm making a program that shows different parts of an image in the same ImageView. But it should wait for some amount of time, about 500 milliseconds, between any two image changes. Like this:

for(int i=1; i<=4;i++){
  for(int j=1;j<=4;j++){
  //code to refresh the image.
  // wait for 500 milliseconds before resuming the normal iteration
  }
}

I tried using the following code:

for(int i=1; i<=4;i++){
  for(int j=1;j<=4;j++){
    //code to refresh the image.
    Thread.sleep(500);
  }
}

But this displays only the last segment of the image, not segment by segment. BTW, each segment is saved as pic1, pic2,pic3.. and so on (they all are different images). I want a solution to display them in the following sequence:

Thanks a ton

Upvotes: 1

Views: 2243

Answers (1)

nneonneo
nneonneo

Reputation: 179717

If this is inside your UI thread loop, you should use an AsyncTask or a Timer to achieve your goals instead, to avoid blocking the UI.

Using AsyncTask:

class UpdateImages extends AsyncTask<Void, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // refresh the image here
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        for(int i=0; i<4; i++) {
            for(int j=0; j<4; j++) {
                // NOTE: Cannot call UI methods directly here.
                // Call them from onProgressUpdate.
                publishProgress(i, j);
                try {
                    Thread.sleep(500);
                } catch(InterruptedException) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
    }
}

then just call

new UpdateImages().execute();

when you want to start this task. Using an AsyncTask this way avoids blocking your UI, and still lets you do whatever you want on schedule.

Upvotes: 3

Related Questions