0

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
}
}
xagyg
  • 9,562
  • 2
  • 32
  • 29
josemfr
  • 15
  • 2

1 Answers1

1

To run a Thread instance in a separate thread, it's Thread#start(), not Thread#run(). Thread#run() will not create a new thread but just run run() in the current thread (which is UI Thread, this is why you get ANR).

Also it's better to implement Runnable than to extend Thread.

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127