Search code examples
javaandroidtimerhandler

Android: How to call certain method after certain time?


I am a newbie to Android App Development. I want to call a certain method after certain time and I am unable to do that. The methods I have tried include the postDelayed method.

Here is the code I want to execute after 2000ms

private void computersTurn() {
    rollButton.setEnabled(false);
    holdButton.setEnabled(false);
    while (currentTurn=='C' && cTurn<=20 && cTotal<=100) {
        rollDice();//TO BE EXECUTED AFTER INTERVALS
    }
    hold();
    rollButton.setEnabled(true);
    holdButton.setEnabled(true);
}

The code for whole activity can be found here: http://pastebin.com/bzkfydpL


Solution

  • Try this code to delay execution of your function:

    private int DELAY = 1500; // Delay time in milliseconds
    
    new Handler().postDelayed(new Runnable() {
               @Override
               public void run() {
                  computersTurn();
               }
             }, DELAY);