0

Another question: Now is posible to start the thread, the problem is this: click button1 and thread start, click button2 and set running to false so thread finish. The problem is if I click button1 again then error and aplication stop.

Please, where is the problem??? Thank 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.start();
        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
}
}
josemfr
  • 15
  • 2

2 Answers2

2

You can't restart threads in Java. You have to create a new one. You are trying to reuse the same one that you stopped previously.

kabuko
  • 36,028
  • 10
  • 80
  • 93
0

You are trying to start an already started thread when clicking next time.

if(!hj.isAlive()) {  
    hj.setRunning(true);
    hj.setTurno(true);
    hj.start();
}