Search code examples
androiddelay

How do I delay some code in Android?


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)


Solution

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