2011-10-15 26 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”。 –