Location Manager Inside Service

Is it possible to request location updates inside a service that is in a separate thread from the one that calls startService?

I have tried:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

It keeps giving me the error:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Can the background manager run inside a service that is in a separate thread, or does the location manager need to be called from an Activity?

Upvotes: 2

Views: 2205

Answers (2)

Artur
Artur

Reputation: 21

I discovered that if you call requestLocationUpdates from service in this manner:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLoclistener, Looper.getMainLooper());

Then you will get the same behavior as if you call it from an activity!!!

Upvotes: 2

devunwired
devunwired

Reputation: 63293

You don't necessarily have to receive the updates on the main thread, but you do have to have a valid Looper that the underlying service can use to pass callbacks through an internal Handler. Inherently, if you do everything on the main thread you're good because this thread has an active Looper already attached.

Have a look at the docs for Looper as they explain how to set up your background thread with a valid instance so it can be used for this purpose. There is also a version of requestLocationUpdates() that takes a Looper object. You could call requestLocationUpdates() while passing the result of Looper.getMainLooper() to allow the callbacks to be processed on the main thread even though you may not be able to attach the listener directly from that thread.

Also, keep in mind that location updates are inherently asynchronous, and are not blocking your main thread just because you register the callbacks there. This may not be the reason you are interested in this, but I thought it worth mentioning.

HTH

Upvotes: 3

Related Questions