I have this project, with 2 classes. activity_main has 2 buttons, button1 runs a thread and I want to stop it with button2, but it does not work, because while the thread is running button2 is not clickable. Finally AVD stops the program. Please, any suggestion???
Thnaks in advance.
activity_main.xml
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="gestionbotones"
android:text="Thread ON" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="gestionbotones"
android:text="Thread OFF" />
MainActivity.java
public class MainActivity extends Activity {
.......
private HiloJuego hj = new HiloJuego();
.......
public void gestionbotones (View v){
int id = v.getId();
switch(id){
case R.id.button1 :
Log.d(TAG, "Thread activado");
hj.setRunning(true);
hj.setTurno(true);
hj.run();
break;
case R.id.button2: // Desactivar
hj.setRunning(false);
Log.d(TAG, "Thread destruído");
break;
default:
break;
}
}
HiloJuego.java
package com.example.tocatoca1;
import android.util.Log;
public class HiloJuego extends Thread {
private static final String TAG = HiloJuego.class.getSimpleName();
private boolean running;
private boolean turno;
public void setRunning(boolean running) {
this.running = running;
}
public void setTurno(boolean turno){
this.turno=turno;
}
public HiloJuego() {
super();
}
@Override
public void run() {
Log.d(TAG, "Starting game loop");
while (running) {
if (turno){
Log.d(TAG, "Turno Ordenador");
} else{
Log.d(TAG, "Turno Jugador");
}
} // end finally
}
}