2012-07-26 2 views
0

나는 스레드는이 방법 안에 checkUpdate를 불렀다 :안드로이드 스레드

public void onLocationChanged(Location location) 
    checkUpdate = new Thread() { 
     public void run() { 
      try { 
       // do some long staff using location variable    
       } catch (Exception e) {} 
      handler.sendEmptyMessage(0); 
     } 
    }; 
    checkUpdate.start(); 

문제는 onLocationChanged() 방법은 시스템에 의해 호출되는 스레드가 완료 때때로 전에이 예기치 않은 동작의 원인이다 내 신청서에.

이미 실행 중이거나 비슷한 경우 스레드를 실행하지 못할 수 있습니까?


해결책 :

내가 무슨 일이 일어나고 있는지, 그렇지 않으면 응용 프로그램이 종료 된 경우에도 서비스가 계속 실행 및 위치를 가져 오는되고, locationManager.removeUpdates(locationListener); 를 호출해야하고 파괴 활동에 대한 locationManager=null을 설정합니다.

답변

1

당신은 스레드를 시작할지 여부를 알려주는 값을 설정하는 AtomicBoolean를 사용할 수있는 이미 실행중인 경우 스레드를 실행하지 않는 방법 또는

비슷한있다. 그런 다음 run() 메서드가 끝날 때 플래그를 false로 재설정 할 수 있습니다. 다음과 같은

뭔가 작동합니다 : 그것은 작동하지 않습니다

private final AtomicBoolean threadStarted = new AtomicBoolean(false); 
... 
public void onLocationChanged(Location location) { 
    if (threadStarted.compareAndSet(false, true)) { 
     // start the thread 
     checkUpdate = new Thread() { 
      public void run() { 
       try { 
        // do thread stuff here 
       } finally { 
        // when the thread finishes, set the started flag to false 
        threadStarted.set(false); 
       } 
      } 
     }; 
     checkUpdate.start(); 
    } 
} 
+0

, threadStarted 내가 코드 @Xenione에 문제가 표시되지 않습니다 항상 – Xenione

+0

false입니다. 스레드가 시작되고 있는지를 알기 위해 몇 가지 로그인 할 수 있습니까? – Gray

+0

확인. 핸들러에 뭔가 문제가있을 수 있습니다. 아마도 처리기 작업이 done.do 일 때 true로 설정해야하기 때문에 threadStarted를 설정해야합니다. thanks – Xenione

관련 문제