2016-04-08 16 views
2

我正試圖寫一個消息給標準輸出在Android每秒舉行一個給定的按鈕(我打算在稍後放置一個方法)。我使用的開關在標準onTouch方法檢測按鈕按下:爲什麼釋放按鈕時工作線程會卡在循環中?

protected void setFab(FloatingActionButton fab) { 
    fab.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch (event.getAction()) { 
       case MotionEvent.ACTION_DOWN: { 
        System.out.println("Button pressed"); 
        handleButtonDown(); 
        return true; 
       } 
       case MotionEvent.ACTION_UP: { 
        System.out.println("Button released"); 
        handleButtonUp(); 
        return true; 
       } 
       default: 
        return true; 
      } 
     } 
    }); 
} 

而全球兩大全球布爾:

private boolean captureThreadRunning = false; 
private boolean cancelCaptureThread = false; 

哪些是停止循環時鬆開按鈕:

public void handleButtonUp() { 
    cancelCaptureThread = true; 
} 

但是,當我啓動工作線程時,即使按鈕被釋放,因此全局布爾值應該被更改,它仍會陷入無限循環:

public void handleButtonDown() { 
    System.out.println("Capture thread running: " + captureThreadRunning); 
    if (!captureThreadRunning) { 
     System.out.println("Thread starting"); 
     startCaptureThread(); 
    } 
} 

public void startCaptureThread() { 
    System.out.println("Thread started"); 
    Thread thread = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       captureThreadRunning = true; 
       System.out.println("Got to try"); 
       while (!cancelCaptureThread) { 
        System.out.println("Success"); 
        try { 
         System.out.println("Falling asleep"); 
         Thread.sleep(1000); 
         System.out.println("Slept 1000"); 
        } catch (InterruptedException e) { 
         throw new RuntimeException(
           "Interrupted.", e); 
        } 
       } 
      } finally { 
       System.out.println("got to finally"); 
       captureThreadRunning = false; 
       cancelCaptureThread = false; 
      } 
     } 
    }); 
    thread.run(); 
} 

不僅如此,但用戶界面也被凍結,這肯定不應該,因爲我正在做一切在一個單獨的線程。當我釋放按鈕時,循環應該停止,因爲布爾變化了。 我對線程和android都很陌生,所以我想我只是錯過了一些東西。

回答

0

但你確實在你的主線程中執行你的代碼。注意你打電話

thread.run(); 

所以你的執行路徑進入一個無限循環。將其更改爲

thread.start(); 

,將開始一個新的Thread

相關問題