2012-08-08 64 views
2

我無法找到任何工作解決方案來在鎖定/解鎖設備時停止/恢復線程,任何人都可以提供幫助,或者告訴我在哪裏可以找到如何操作的方法?我需要在手機鎖定時停止線程,並在手機解鎖時再次啓動。開始/停止線程

+0

你已經有了監聽鎖定/解鎖事件的代碼嗎? – 2012-08-08 13:24:34

+0

是的,但我不知道它是正確的,你可以給一個鏈接,或源的例子如何正確地做到這一點? – 2012-08-08 14:00:03

回答

8

Java在協作中斷模型上運行以停止線程。這意味着你不能簡單地在線程本身沒有合作的情況下停止線程執行。如果你想停止一個線程客戶端可以調用了Thread.interrupt()方法來請求的線程停止:

public class SomeBackgroundProcess implements Runnable { 

    Thread backgroundThread; 

    public void start() { 
     if(backgroundThread == null) { 
      backgroundThread = new Thread(this); 
      backgroundThread.start(); 
     } 
    } 

    public void stop() { 
     if(backgroundThread != null) { 
      backgroundThread.interrupt(); 
     } 
    } 

    public void run() { 
     try { 
      Log.i("Thread starting."); 
      while(!backgroundThread.interrupted()) { 
       doSomething(); 
      } 
      Log.i("Thread stopping."); 
     } catch(InterruptedException ex) { 
      // important you respond to the InterruptedException and stop processing 
      // when its thrown! Notice this is outside the while loop. 
      Log.i("Thread shutting down as it was requested to stop."); 
     } finally { 
      backgroundThread = null; 
     } 
    } 

螺紋的重要組成部分,是你不要嚥下InterruptedException的,而是阻止你的線程的循環,因爲只有當客戶端自己請求線程中斷時纔會發生此異常。

因此,您只需要將SomeBackgroundProcess.start()連接到解鎖事件,並將SomeBackgroundProcess.stop()連接到鎖定事件。

+0

這很好,但工作只有沒有if(backgroundThread == null),但線程粉碎,如果去電話菜單(隱藏應用程序,然後再次打開) – 2012-08-09 13:10:19

+0

我不明白你想說的除了你必須刪除if(backgroundThread == null)。這可能是一個競爭條件,線程在你打開電話菜單之前沒有關閉,所以線程正在死亡,但它還沒有達到最終的聲明。在開始/停止中添加日誌語句,然後檢查日誌以查看是否是這種情況。 – chubbsondubs 2012-08-09 14:31:49