requestLocationUpdates() in separate Thread

假装没事ソ 提交于 2019-11-30 15:28:59

问题


I need requestLocationUpdates() to be in a separate Thread, in order to not have it blocking the rest of my application (it will run most of the time). What is the best way to do it?


回答1:


When you call requestLocationUpdates() this just indicates that you want to be called back when the user's location changes. This call doesn't take a significant amount of time and can be made on the main thread.

When the user's location changes (and based on the criteria you pass to requestLocationUpdates()) your listener will be called back via onLocationChanged() or notified via Intent (depending on which parameters you pass to requestLocationUpdates()). If you do a lot of processing in onLocationChanged() then you shouldn't run this method on the main thread, but you should just start a background thread (or post a Runnable to a background thread and do your work on the background thread.

Another option is to start a HandlerThread and provide the Looper from the HandlerThread as a parameter to requestLocationUpdates(). In that case, the callbacks to onLocationChanged() will be made on the HandlerThread. This looks something like this:

    HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
    handlerThread.start();
    // Now get the Looper from the HandlerThread
    // NOTE: This call will block until the HandlerThread gets control and initializes its Looper
    Looper looper = handlerThread.getLooper();
    // Request location updates to be called back on the HandlerThread
    locationManager.requestLocationUpdates(provider, minTime, minDistance, listener, looper);


来源:https://stackoverflow.com/questions/29219144/requestlocationupdates-in-separate-thread

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