Android:LocationManager构造函数的looper

Mas*_*imo 2 android location locationmanager looper

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

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
Run Code Online (Sandbox Code Playgroud)

文档使用以下单词解释属性:

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
Run Code Online (Sandbox Code Playgroud)

如果我想用这种方法开始接收更新,我无法理解类(looper)的行为.

此外,我正在类LocationManager创建一个库,在执行正常行为之前,我需要做一些其他的工作.比我需要的是开始接收库的LocationListener上的更新,并且只有在验证某些条件时才执行正常行为.

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

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

Joh*_*ine 13

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

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

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper)
Run Code Online (Sandbox Code Playgroud)

或者打电话

requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
Run Code Online (Sandbox Code Playgroud)

在Android位置管理器内部,它设置一个ListenerTransport对象,为所提供的looper或主线程(如果没有提供)创建Handler.此处理程序从LocationManager提供程序接收侦听器事件.

通常,如果要在AsyncTask中处理位置管理器事件,或者如果要在侦听器中执行长时间运行的操作并避免阻止UI线程,则可以使用Looper向侦听器请求更新.一个简单的例子如下:

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

在您的LocationLiistener中

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):
        }
     });
}
Run Code Online (Sandbox Code Playgroud)