gpt4 book ai didi

android - 未调用 handleMessage

转载 作者:搜寻专家 更新时间:2023-11-01 09:11:48 25 4
gpt4 key购买 nike

我有一个试图获取用户位置的线程。

当接收到位置时,“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com