Although GPSmaster's answer is accepted, I want to post the link to more elegant and simpler solution, I think - https://gist.github.com/777790/86b405debd6e3915bfcd8885c2ee11db2b96e3df. I have tried it myself and it worked =)
In case the link doesn't work, this is a custom LocationListener
by amay077:
/**
* Initialize instance.
*
* @param locaMan the base of LocationManager, can't set null.
* @param timeOutMS timeout elapsed (mili seconds)
* @param timeoutListener if timeout, call onTimeouted method of this.
*/
public TimeoutableLocationListener(LocationManager locaMan, long timeOutMS,
final TimeoutLisener timeoutListener) {
this.locaMan = locaMan;
timerTimeout.schedule(new TimerTask() {
@Override
public void run() {
if (timeoutListener != null) {
timeoutListener.onTimeouted(TimeoutableLocationListener.this);
}
stopLocationUpdateAndTimer();
}
}, timeOutMS);
}
/***
* Location callback.
*
* If override on your concrete class, must call base.onLocation().
*/
@Override
public void onLocationChanged(Location location) {
stopLocationUpdateAndTimer();
}
@Override
public void onProviderDisabled(String s) { }
@Override
public void onProviderEnabled(String s) { }
@Override
public void onStatusChanged(String s, int i, Bundle bundle) { }
private void stopLocationUpdateAndTimer() {
locaMan.removeUpdates(this);
timerTimeout.cancel();
timerTimeout.purge();
timerTimeout = null;
}
public interface TimeoutLisener {
void onTimeouted(LocationListener sender);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…