2013-04-30 78 views
0

我有這個項目,有2個類。 activity_main有2個按鈕,button1運行一個線程,我想用button2停止它,但它不起作用,因爲當線程運行時,button2是不可點擊的。最後AVD停止該程序。請任何建議?線程故障

提前提示。

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 
} 
} 
+0

您的mainactivity.java只運行一次。 – 2013-04-30 14:57:08

+1

@AsierAranbarri和? – m0skit0 2013-04-30 15:01:57

+0

+1爲自蠢 – 2013-04-30 15:04:16

回答

1

在一個單獨的線程中運行一個實例Thread,它Thread#start(),不Thread#run()Thread#run()不會創建一個新線程,而只是在當前線程中運行run()(這是UI線程,這就是爲什麼你會得到ANR)。

it's better to implement Runnable than to extend Thread

+0

謝謝你m0skit0。 – josemfr 2013-04-30 15:18:32