我的应用程序在特定时间检查用户是否在指定位置.我使用警报管理器启动进行此调用的服务:
locationManager.requestLocationUpdates(bestProvider,listener);
并检查:
locationManager.getLastKNownLocation(bestProvider);
但是我在真实设备上运行时遇到了问题.首先,getLastKNownLocation很可能是GPS所在的最后一个位置,可能是任何地方(即,它可能距离用户的当前位置数英里).所以我只是等待requestLocationUpdates回调,如果它们在两分钟内不存在,则删除监听器并放弃,对吧?
错了,因为如果用户的位置已经稳定(即,他们最近使用过GPS并且没有移动过),那么我的听众永远不会被调用,因为位置没有改变.但GPS将一直运行,直到我的听众被移除,耗尽电池……
获取当前位置的正确方法是什么,而不会误认为当前位置的旧位置?我不介意等几分钟.
编辑:有可能我错误的是没有被叫的听众,它可能只需要比我想象的要长一点……很难说.我仍然很欣赏一个确定的答案.
解决方法
代码可能是这样的:
public class MyLocation {
Timer timer1;
LocationManager lm;
public boolean getLocation(Context context)
{
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,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而不是计时器.