user4096893
user4096893

Reputation:

Pause Android app until button press

I have two methods: go() and stop(), and a for loop looping through these methods 3 times. go() activates automatically when the loop starts and stop() will only activate once a button is pressed 3 times:

private static int buttonPress;

for (int i = 0; i < 3, i++) {
    go();
    do {} while(pressCount < 4);
    stop();
}

Whenever the button the pressed, pressCount is incremented by 1:

public void button(View v) {
    pressCount++;
}

The problem is that with this setup, when the do while loop launches, the app freezes and crashes.

Is there any way to fix this while still having the go() activate before stop(), having stop() activate after pressCount is greater than 3, and looping through 3 times?

Thanks

Upvotes: 0

Views: 1988

Answers (3)

TuomasK
TuomasK

Reputation: 502

You cannot pause main thread, the app freezes.

private int loopCount = 0;
private int pressCount = 0;

public void button(View v) { /* Runs when button is clicked */
    if (loopCount < 4){
        pressCount++;

        if (pressCount == 3){
            pressCount = 0;
            loopCount++;
            stop();
        }
    }
}

This code runs stop() when the button is pressed three times, but runs that only three times. (After 9 presses nothing happens)

Upvotes: 0

Vigen
Vigen

Reputation: 503

try this

private boolean isStop = true;
private int buttonPressedCount = 0;

private void goOrStop() {
    if(isStop) {
      go();
      isStop = false;
    } else {
       stopIfCan(); // :)
    }
}

private void stopIfCan() {
    if(buttonPressedCount >= 3 ) {
        buttonPressedCount = 0; 
        isStop = false;
        stop();
    }
}

public void button(View v) {
    buttonPressedCount++;
}

Upvotes: 0

Aqib
Aqib

Reputation: 396

you cannot block the main thread for more than 5 seconds if that happens then an anr (Application not responding) dialog pops up.

Upvotes: 3

Related Questions