2014-03-25 69 views
0

我创建了一个按钮,现在我想添加,如果我点击它,线程应该睡觉。现在我有问题,如果我点击按钮,程序没有睡觉。我通过添加另一个背景来测试按钮的功能。停止线程按钮

ToggleButton t; 
LinearLayout l; 
boolean pausegedrückt; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    tts = new TextToSpeech(this, this); 
    pausegedrückt=false; 

public void Crunch(int anzahl) { 


     setContentView(R.layout.crunch); 

     //Start und Stop Button 
      t=(ToggleButton) findViewById(R.id.toggleButton1); 
      t.setOnCheckedChangeListener(this); 
      l=(LinearLayout)findViewById(R.id.layout); 

     while (pausegedrückt) { 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     }    
     tts.speak("Übung Grandsch: In 10 Sekunden geht`s los! Mach dich bereit!", TextToSpeech.QUEUE_ADD, null); 
     tts.playSilence(9000, TextToSpeech.QUEUE_ADD, null); 
     tts.speak("Los gehts!", TextToSpeech.QUEUE_ADD, null); 
     tts.speak("Mache" + anzahl + "Wiederholungen!" , TextToSpeech.QUEUE_ADD, null); 
     for (int i = 1; i < anzahl+1; i++) { 
       String str = String.valueOf(i); 
       tts.speak(str, TextToSpeech.QUEUE_ADD, null); 
       tts.playSilence(3000, TextToSpeech.QUEUE_ADD, null); } 
     tts.speak("Übung beendet!", TextToSpeech.QUEUE_ADD, null); 


    } 

@Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      l.setBackgroundColor(Color.BLUE); 
      pausegedrückt=true; 
     } else { 
      l.setBackgroundColor(Color.BLACK); 
      pausegedrückt=false; 
     } 

    } 
+1

哪里是线程的正确方法?你正在调用ui线程的睡眠? – Raghunandan

+0

方法紧缩被另一个类调用。我是否需要在线程中设置整个方法? – basti12354

+0

非常混乱。另一类。是活动课吗?你在说什么线程 – Raghunandan

回答

0

这是创建一个线程

Thread timer = new Thread() { 
     @Override 
     public void run() { 
      try { 
       //try something here 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
     } 
    }; 
    timer.start(); 

让你的线程休眠

timer.sleep(1000);