我有一个线程尝试获取用户位置。
当接收到位置时,调用“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);
}
}
最佳答案
发生这种情况很可能是因为您在将消息发布到 Handler
后立即调用 Looper.quit()
。这会在 Handler
有机会处理消息队列操作之前有效地终止该操作。向 Handler
发送消息只需将其发布到消息队列即可。处理程序将在 Looper 的下一次迭代中检索消息。如果您的目标是在收到位置更新后终止线程,那么最好从 handleMessage()
内部调用 Looper.quit()
。
社论
此外,如果建立该线程的唯一目的是等待位置更新,则没有必要。 LocationManager.requestLocationUpdates()
本质上是一个异步过程(在获取位置修复时,主线程不会被阻塞)。您可以安全地让您的 Activity/Service 直接实现 LocationListener
并在那里接收位置值。
HTH
关于android - 未调用handleMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778746/