0

Before anyone points to it, I have read this answer about Handler and this question builds apon it.

My code looks like this

Handler timerHandler =new Handler();
Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {//stuff that is called iteratively and needs delay before every iteration
        do some stuff;
        if(ExitCodition){
            timerHandler.removeCallbacks(timerRunnable);
        }
        else {//call that stuff again
            timerHandler.postDelayed(this, 500);
        }
    }
};
someMethodCalledOnButtonClick(){
    //do foo;
    timerHandler.postDelayed(timerRunnable,500);
    //do bar;
}

What I need is that when someMethodCalledOnButtonClick() is called, the execution occurs as

  1. foo 2.the stuff that needs delay 3. bar

What I see is that the code that needs delay is actually running independent of the later code (bar), so the bar code gets executed while the handler code is getting executed in parallel.

How do I ensure that code gets executed in proper order? All I need is to add delay in execution of every iteration of some code(without delay, I could have simply used a while loop)

Community
  • 1
  • 1
Registered User
  • 2,239
  • 3
  • 32
  • 58
  • You can use msg.what to distinguish different task, when your timerRunnable is finished, send a msg to handler to execute code about "do bar". – Veer Aug 27 '16 at 16:00

3 Answers3

0

How do I ensure that code gets executed in proper order?

Move the logic named "bar" into the run() method of timerRunnable.

If the method name someMethodCalledOnButtonClick is literal — that this method is called on the main application thread in response to a button click — then you do not want to be blocking the main application thread in someMethodCalledOnButtonClick(). After all, that prevents timerRunnable from actually running.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

Handler will execute its code asynchronously, it will run in another thread. Try putting //do bar code inside the handler and see if you get what you want :)

Handler timerHandler =new Handler();
Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {//stuff that is called iteratively and needs delay before every iteration
        do some stuff;
        if(ExitCodition){
            timerHandler.removeCallbacks(timerRunnable);
        }
        else {//call that stuff again
            timerHandler.postDelayed(this, 500);
           //do bar; // YOUR CODE HERE
        }
    }
};
someMethodCalledOnButtonClick(){
    //do foo;
    timerHandler.postDelayed(timerRunnable,500);
}
Augusto Carmo
  • 4,386
  • 2
  • 28
  • 61
0

To make a delay you can use:

SystemClock.sleep(timeInMills);

This is just a sleep function.

Yunus1903
  • 1
  • 3