How to set delay in android?

android, java

Solution

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

Problem

``` public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.rollDice: Random ranNum = new Random(); int number = ranNum.nextInt(6) + 1; diceNum.setText(""+number); sum = sum + number; for(i=0;i<8;i++){ for(j=0;j<8;j++){ int value =(Integer)buttons[i][j].getTag(); if(value==sum){ inew=i; jnew=j; buttons[inew][jnew].setBackgroundColor(Color.BLACK); //I want to insert a delay here buttons[inew][jnew].setBackgroundColor(Color.WHITE); break; } } } break; } } ``` I want to set a delay between the command between changing background. I tried using a thread timer and tried using run and catch. But it isn't working. I tried this ``` Thread timer = new Thread() { public void run(){ try { buttons[inew][jnew].setBackgroundColor(Color.BLACK); sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }; timer.start(); buttons[inew][jnew].setBackgroundColor(Color.WHITE); ``` But it is only getting changed to black.

Original source

Related problems