2

可以使用以下方法开始从 LocationManager 检索通知:

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)

文档用这些词解释属性:

provider    the name of the provider with which to register
minTime     minimum time interval between location updates, in milliseconds
minDistance minimum distance between location updates, in meters
listener    a LocationListener whose onLocationChanged(Location) method will be called for each location update
looper      a Looper object whose message queue will be used to implement the callback mechanism, or null to make callbacks on the calling thread

如果我想开始使用这种方法接收更新,我不能很好地理解类(looper)的行为。

此外,我正在围绕类 LocationManager 创建一个库,并且在执行正常行为之前,我需要做一些其他工作。我需要的是开始接收库的 LocationListener 更新,而不是仅在验证某些条件后才执行正常行为。

为了做到这一点,如果用户开始使用上述方法接收更新,我需要知道如何模拟具有 LocationManager 的行为。

我希望我很清楚。有人能帮我吗?谢谢!

4

1 回答 1

13

Looper 基本上是一个在后台运行的线程,只要它从 Handler 对象接收到消息或可运行,它就会工作。主循环器是 UI 线程的一部分。其他looper通常是通过构造new HandlerThread然后调用thread.start(),然后调用thread.getLooper()来创建的。

LocationManager 允许您使用特定的 Looper 或在主 Looper(UI 线程)上请求位置。

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)

或致电

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

在 Android 位置管理器内部,它设置了一个 ListenerTransport 对象来为提供的 looper 创建一个处理程序,如果没有提供,则在主线程上创建一个处理程序。此处理程序从 LocationManager 提供程序接收侦听器事件。

通常,当您想在 AsyncTask 中处理位置管理器事件或想要在侦听器中执行长时间运行的操作并避免阻塞 UI 线程时,您将使用 Looper 请求更新侦听器。一个简单的例子如下:

HandlerThread t = new HandlerThread("my handlerthread");
t.start();
locationManager.requestLocationUpdates(locationManager.getBestProvider(), 1000l, 0.0f, listener, t.getLooper());

在您的 LocationListener 内

Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());
@Override
public void onLocationChanged(Location location) {
     final MyPojoResult result = doSomeLongRuningOperation(location);
     MAIN_HANDLER.post( new Runnable() { 
        @Override
        public void run() {
           doSomeOperationOnUIThread(result):
        }
     });
}
于 2014-11-03T14:09:20.293 回答