2012-08-08 3 views
2

장치를 잠 그거나 잠금을 해제 할 때 스레드를 중지/다시 시작하는 데 필요한 해결책을 찾지 못했습니다. 아무도 도와 줄 수 있습니까? 아니면 어떻게 할 수 있습니까? 전화가 잠겨있을 때 실을 멈추고 전화기가 잠겨있을 때 다시 시작해야합니다.스레드 시작/중지

+0

이미 잠금/잠금 해제 이벤트를 수신하는 코드가 있습니까? –

+0

네, 맞습니다, 링크를 줄 수 있습니까? 아니면 예를 들어 어떻게 올바르게 할 수 있습니까? –

답변

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)가 아닌 경우에만 작동하지만 휴대 전화 메뉴로 이동하면 숨 깁니다 (숨겨진 앱을 연 다음 다시 열 수 있음) –

+0

삭제해야하는 것 이외의 다른 말을 이해하지 못합니다. if (backgroundThread == null) 스레드가 죽어 가도록 전화 메뉴를 누르기 전에 스레드가 종료되지 않았지만 finally 문에 도달하지 않은 경합 상태 일 수 있습니다. 시작/중지에 로그 문을 추가 한 다음 로그를 확인하여 해당되는 경우 확인하십시오. – chubbsondubs