Reputation: 17915
I have regular service that I start using alarms every 5 minutes. Service Implements LocationListener to get GPS fix and save it into SqLite database.
I give service 1 minute to get best fix possible. If I get accuracy <20 before that - even better.
All that works fine. I also have code that checks if GPS disabled so I exit service.
What I want to do is: If there is no fix within 1 minute - I want to exit service. Currently since most logic (time checks, etc) is in onLocationChanged - I never have chance to do so because I never get location.
Is there timer or something like that I can use? I'm new to Java, example would be nice. I see it like this: On start I create timer with callback and in this callback function I will cleanup and shutdown. I'm not sure if there going to be any implications with possible onLocationChanged running?
Can I possibly disable timer as soon as I get onLocationChanged?
Upvotes: 3
Views: 1794
Reputation: 1409
Use a android.os.Handler:
Handler timeoutHandler = new Handler();
timeoutHandler.postDelayed(new Runnable() {
public void run() {
stopSelf();
}
}, 60 * 1000);
Upvotes: 3
Reputation: 145
You could schedule a timeout using Timer and TimerTask as follows...
Declare a global Timer object reference in your Service:
Timer timeout = null;
In onStartCommand(), instantiate this Timer and schedule a TimerTask to execute in one minute. Do this after you've registered for location updates from the desired provider:
timeout = new Timer();
timeout.schedule(timeoutTask, 60000);
Define timeoutTask somewhere in your Service class e.g:
private TimerTask timeoutTask = new TimerTask() {
public void run() {
// Handle timeouts here
}
}
If you get a callback via onLocationChanged() before the Timer expires, you'll want to stop timeoutTask from being executed, so inside onLocationChanged():
if(timeout != null) {
timeout.cancel()
}
Then just handle your location inside onLocationChanged() as normal, or call another method to do it, up to you.
There are probably better ways to do it, but this is straightforward and has worked for me on my project :) Hope it helps you too.
All the best, Declan
Upvotes: 1