Question

I created a button, now I want to add, if I click it the thread should sleep. Now I have the problem that the programm isn't sleeping, if I click the button. The work of the button I test by adding set another background.

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;
        }

    }
Was it helpful?

Solution

this is the right way to create a thread

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

to make your thread sleeps

timer.sleep(1000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top