Further to Merlin's answer (I was just typing this lot out in notepad when it appeared) - I agree. My suggestion is:
Facing a similar problem, I decided that the best thing to do would be to decouple the whole GPS from the main activity by means of a service.
By this I mean have a service which does the requestsLocationUpdates()
and removeLocationUpdates()
and implements a LocationListener
. This service provides methods which the main activity can call by means of an IBinder
interface. It also sends broadcasts to the activity which implements a BroadcastReceiver
to listen to these messages.
So one of the the service methods your main activity could call would be (say)
mLocnServ.startGPS(int timeout, float requiredAccuracy, int minUpdatePeriod, int minResendDistance)
where mLocnServ
is the binder interface exposed by the service.
The last two arguments being those to pass as arguments to requestLocationUpdates in the service. (personally I don't think these make any difference whatsoever to when the GPS turns itself off, as far as I can see it runs all the time until removeUpdates()
is called). Anyway the first argument (timeout) should be the time you are prepared to wait for a fix of the required accuracy (argument 2).
So in your service you will need a Runnable as a timer, which if it times out wil send a broadcast of type TIMED_OUT
(say) and removeUpdates to stop the GPS. In your onLocationChanged you can test the location you get against the required accuracy and if good enough, send a broadcast of type GOT_A_FIX
(say) and pass the location (lat/lon and accuracy) as extras in the broadcast, then removeUpdates to stop the GPS. (TIMED_OUT
and GOT_A_FIX
are just example names for enums which you can make up to distinguish between the broadcast message types)
The main activity can decide what to do then in its BroadcastReceiver onReceive(), i.e whether to try again if it got a TIMED_OUT
broadcast or what to do with the data it got from the GOT_A_FIX
message.
You'll probably also need a mLocnServ.stopGPS
in the binder so that you can shut the GPS no matter what the service is doing