android 未调用消息

rbpvctlc  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(136)

我有一个线程,试图获得用户的位置。
当接收到位置时,将调用“handler.sendMessage(msg)”,并返回true,但不会调用sendMessage。
logcat中没有错误或警告。
代码:

  1. public class LocationThread extends Thread implements LocationListener {
  2. // ... Other (non-relevant) methods
  3. @Override
  4. public void run() {
  5. super.run();
  6. Looper.prepare();
  7. mainHandler = new Handler(Looper.myLooper()) {
  8. @Override
  9. public void handleMessage(Message msg) {
  10. // This method is never called
  11. }
  12. };
  13. locationManager.requestLocationUpdates(
  14. LocationManager.NETWORK_PROVIDER, 0, 0, this);
  15. Looper.loop();
  16. }
  17. @Override
  18. public void onLocationChanged(Location location) {
  19. // SendMessage is executed and returns true
  20. mainHandler.sendMessage(msg);
  21. if (mainHandler != null) {
  22. mainHandler.getLooper().quit();
  23. }
  24. locationManager.removeUpdates(this);
  25. }
  26. }

字符串

kkbh8khc

kkbh8khc1#

发生这种情况的原因很可能是您在将消息发布到Handler之后立即调用了Looper.quit()。这实际上在Handler有机会处理消息之前就终止了消息队列操作。向Handler发送消息只是将其发布到消息队列。处理程序将在Looper的下一次迭代中检索消息。如果您的目标是在收到位置更新后终止线程,那么从handleMessage()内部调用Looper.quit()可能会更好。

社论

此外,如果启动此线程的唯一目的是等待位置更新,那么这是不必要的。LocationManager.requestLocationUpdates()本质上是一个异步进程(在获取位置修复时,主线程不会被阻塞)。您可以安全地让Activity/Service直接实现LocationListener并在那里接收位置值。
HTH

相关问题