2011-10-15 62 views
2

我有一個線程,試圖獲取用戶的位置。handleMessage不叫

當收到位置「handler.sendMessage(msg)」被調用時,它返回true,但handleMessage永遠不會被調用。

logcat中沒有錯誤或警告。

代碼:

public class LocationThread extends Thread implements LocationListener { 
    // ... Other (non-relevant) methods 

    @Override 
    public void run() { 
     super.run(); 

     Looper.prepare(); 
     mainHandler = new Handler(Looper.myLooper()) { 
      @Override 
      public void handleMessage(Message msg) { 
       // This method is never called 
      } 
     }; 
     locationManager.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, 0, 0, this); 
     Looper.loop(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // SendMessage is executed and returns true 
     mainHandler.sendMessage(msg); 
     if (mainHandler != null) { 
      mainHandler.getLooper().quit(); 
     } 
     locationManager.removeUpdates(this); 
    } 
} 
+0

你寫onlocation被改變檢查的設備...... –

+0

你嘗試具有的handleMessage方法退出循環? – Fildor

+0

我剛剛嘗試過,但沒有什麼區別。 –

回答

3

最有可能發生這種情況,因爲您發佈消息到Handler後立即調用Looper.quit()。這在Handler有機會處理它之前有效地終止消息隊列操作。發送消息到Handler只需將其發送到消息隊列。處理程序將在Looper的下一次迭代中檢索消息。如果您的目標是在收到位置更新後終止線程,則最好從handleMessage()內撥打Looper.quit()

編輯

此外,如果站起來這個線程的唯一目的就是等待位置更新進來,這是不必要的。 LocationManager.requestLocationUpdates()是一種固有的異步過程(您的主線程在獲取位置鎖定時未被阻止)。您可以安全地讓您的活動/服務直接執行LocationListener並在那裏接收位置值。

HTH

+0

第一種解決方案對我不起作用,也許是因爲我正在線程中運行線程。儘管如此,第二個解決方案(無論如何都是更好的)確實爲我工作。 我刪除了所有線程相關的東西,只是在方法中調用runnable:「onLocationChanged」。 –