Android GPS timeout
Posted
by Scott Saunders
on Stack Overflow
See other posts from Stack Overflow
or by Scott Saunders
Published on 2010-06-07T19:44:55Z
Indexed on
2010/06/07
20:32 UTC
Read the original article
Hit count: 1022
I'm writing an Android application that, among other things, needs to send the current GPS coordinates to a server when the user tells it to. From a context menu, I run the service below. The service is a LocationListener and requests updates from the LocationManager. When it gets a location (onLocationChanged()), it removes itself as a listener and sends the coordinates off to the server. All of this is working.
However, if GPS coordinates are not quickly available, my service just keeps running until it gets some. It holds up the UI with a progress dialog, which is annoying. Worse, if the user has moved since starting the service, the first GPS coordinates might be wrong and the app will send bad data to the server.
I need a timeout on the service. Is there a good way to do that? I'm not very experienced with threads. I think I can run a Runnable in the onStartCommand() method that will somehow count down 30 seconds and then, if there is no GPS result yet, call my service's stop() method. Does that sound like the best way to do this?
Alternatively, is it possible to tell if the GPS cannot get a fix? How would I go about doing that?
Edit: To further clarify, I'm looking for the best way to "give up" on getting a Location after some amount of time.
public class AddCurrentLocation extends Service implements LocationListener {
Application app;
LocationManager mLocManager;
ProgressDialog mDialog;
@Override
public int onStartCommand(Intent intent, int arg0, int arg1) {
app = getApplication();
// show progress dialog
if (app.getScreen() != null) {
mDialog = ProgressDialog.show(app.getScreen(), "", "Adding Location. Please wait...", true);
}
// find GPS service and start listening
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String bestProvider = mLocManager.getBestProvider(criteria, true);
mLocManager.requestLocationUpdates(bestProvider, 2000, 0, this);
return START_NOT_STICKY;
}
private void stop() {
mLocManager.removeUpdates(this);
if (mDialog != null) {
mDialog.dismiss();
}
stopSelf();
}
@Override
public void onLocationChanged(Location location) {
// done with GPS stop listening
mLocManager.removeUpdates(this);
sendLocation(location); // method to send info to server
stop();
}
// other required methods and sendLocation() ...
}
© Stack Overflow or respective owner