【问题标题】:Pause Android app until button press暂停 Android 应用程序,直到按下按钮
【发布时间】:2015-02-25 16:54:56
【问题描述】:

我有两个方法:go() 和 stop(),还有一个 for 循环遍历这些方法 3 次。 go() 会在循环开始时自动激活,而 stop() 只会在按下按钮 3 次后激活:

private static int buttonPress;

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

每当按下按钮时,pressCount 就会增加 1:

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

问题在于,在这种设置下,当 do while 循环启动时,应用程序会冻结并崩溃。

有什么办法可以解决这个问题,同时在 stop() 之前激活 go(),在 pressCount 大于 3 之后激活 stop(),并循环 3 次?

谢谢

【问题讨论】:

    标签: java android android-studio do-while buttonclick


    【解决方案1】:

    如果发生这种情况,您不能阻塞主线程超过 5 秒,然后会弹出一个 anr(应用程序无响应)对话框。

    【讨论】:

    • 那么为什么要在不阻塞主线程的情况下“暂停”应用程序?
    • 使用闹钟、计时器或任何其他方式。
    【解决方案2】:

    您不能暂停主线程,应用程序会冻结。

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

    此代码在按钮被按下三次时运行stop(),但只运行三次。 (按 9 次后没有任何反应)

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

      • 问题在于 stop() 必须在三个 buttonPress 之后执行,使用 if 语句,如果 buttonPress 小于 3,程序将跳过 stop() 而不是等待跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2019-09-27
      相关资源
      最近更新 更多