I have a problem with the use of threads in android.
It's very simple, I have a table with buttons on the screen. I try that, randomly, one changes color and after half a second, return to the original color, so that at the moment another one is lit again.
The part that gives me problems is with the threads:
class colores extends AsyncTask<String,String,String>{
private AppCompatActivity actividad;
private int aleatorio;
public colores(AppCompatActivity cx){
this.actividad=cx;
}
public void generarAleatorio(){
aleatorio = (int) (Math.random() * (28 - 0) + 0);
}
@Override
protected String doInBackground(String... params) {
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
generarAleatorio();
runOnUiThread(new Runnable() {
@Override
public void run() {
boton[aleatorio].setBackgroundColor(Color.YELLOW);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
boton[aleatorio].setBackgroundColor(Color.WHITE);
}
});
}
}
}).start();
return null;
}
}
The previous code would be inside another class
("button" is an array of Button
and 28 is random because of the size of said array).
The problem I have is that I change color only to yellow, then for half a second and put another button in yellow, without replacing the last change in white. The result is that everyone ends up in yellow without going through the target.
Could it be the problem of Thread.sleep()
in conjunction with the two runOnUiThread()
?