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?
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.
Before requesting location updates, your app must connect to location services and make a location request. The lesson on Changing Location Settings shows you how to do this. Once a location request is in place you can start the regular updates by calling requestLocationUpdates () .
Register for location updates using a provider selected through the given Criteria, and callbacks delivered via the provided PendingIntent. minimum time interval between location updates in milliseconds Java documentation for android.location.LocationManager.requestLocationUpdates (long, float, android.location.Criteria, android.app.PendingIntent).
Once a location request is in place you can start the regular updates by calling requestLocationUpdates () .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With