我有一个线程,试图获得用户的位置。
当接收到位置时,将调用“handler.sendMessage(msg)”,并返回true,但不会调用sendMessage。
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);
}
}
字符串
1条答案
按热度按时间kkbh8khc1#
发生这种情况的原因很可能是您在将消息发布到
Handler
之后立即调用了Looper.quit()
。这实际上在Handler
有机会处理消息之前就终止了消息队列操作。向Handler
发送消息只是将其发布到消息队列。处理程序将在Looper
的下一次迭代中检索消息。如果您的目标是在收到位置更新后终止线程,那么从handleMessage()
内部调用Looper.quit()
可能会更好。社论
此外,如果启动此线程的唯一目的是等待位置更新,那么这是不必要的。
LocationManager.requestLocationUpdates()
本质上是一个异步进程(在获取位置修复时,主线程不会被阻塞)。您可以安全地让Activity/Service直接实现LocationListener
并在那里接收位置值。HTH