Reputation: 121
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?
Upvotes: 12
Views: 5548
Reputation: 95578
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);
Upvotes: 28