Android: LocationManager constructor's looper

ぃ、小莉子 提交于 2019-12-03 21:03:52

A Looper is basically a thread that runs in the background and does work whenever it receives message or runnable from a Handler object. The main looper is part of the UI thread. Other loopers are usually created by contructing new HandlerThread and then calling thread.start(), followed by thread.getLooper().

LocationManager allows you to request location with a specific Looper or on the main Looper (UI thread).

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

or call

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

Internally in Android Location manager it sets up a ListenerTransport object to create a Handler for the looper provided or on the main thread if none is provided. This handler receives the listener events from the LocationManager providers.

Typically you will request updates to your listener with a Looper when you want to process location manager events inside an AsyncTask or if you want to perform long running operations inside your listener and avoid blocking the UI thread. A simple example follows:

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

Within your 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):
        }
     });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!