我的应用会在特定时间检查用户是否在指定位置。我使用警报管理器启动拨打此电话的服务:
locationManager.requestLocationUpdates(bestProvider, 0, 0, listener);
并检查:
locationManager.getLastKnownLocation(bestProvider);
但是我在真实设备上运行时遇到了问题。首先,getLastKnownLocation
很可能是GPS所在的最后一个地方,可能是任何地方(即,它可能距离用户的当前位置数英里)。所以我只等待requestLocationUpdates
回调,如果它们在两分钟内不存在,请删除听众并放弃,对吧?
错误,因为如果用户的位置已经稳定(即他们最近使用过GPS并且没有移动过),那么我的听众将永远不会被调用,因为该位置不会改变。但GPS将一直运行,直到我的听众被移除,耗尽电池......
获取当前位置的正确方法是什么,而不会误解当前位置的旧位置?我不介意等几分钟。
编辑:我可能错误地认为听众没有被调用,可能只需要比我想象的要长一点......很难说。我仍然很欣赏一个确定的答案。答案 0 :(得分:4)
如果用户的位置已经稳定,则getLastKnownLocation
将返回当前位置。我先调用getLastKnownLocation
,查看时间戳(将Location.getElapsedRealTimeNanos()
与SystemClock.elapsedRealTimeNanos()
进行比较),然后在修复程序太旧时注册一个侦听器。
答案 1 :(得分:4)
代码可能是这样的:
public class MyLocation {
Timer timer1;
LocationManager lm;
public boolean getLocation(Context context)
{
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
lm.removeUpdates(this);
//use location as it is the latest value
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
@Override
public void run() {
lm.removeUpdates(locationListenerGps);
Location location=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//use location as we have not received the new value from listener
}
}
}
我们启动监听器并等待更新一段时间(在我的示例中为20秒)。如果我们在此期间收到更新,我们会使用它。如果我们在此期间没有收到更新,我们使用getLastKnownLocation值并停止监听器。
您可以在此处查看我的完整代码What is the simplest and most robust way to get the user's current location on Android?
编辑(由提问者):这是答案的大部分内容,但我的最终解决方案使用的是Handler而不是计时器。