我正在创建一个应用程序,当用户单击按钮时只检查位置。android getLastKnownLocation()返回总是返回空
这里是我的代码,当我打电话getLastKnownLocation返回null,即使我打电话requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
设备上的定位服务已启用。 非常感谢!
LastKnownLocation返回最后一个已知的修复。所以它有可能是空的。尝试看看这里http://stackoverflow.com/questions/7423624/how-reliable-is-locationmanagers-getlastknownlocation-and-how-often-is-it-updat – alekz
我试图requestLocationUpdates,它并没有实际更新最后一个我知道的位置。 –
你有没有找到解决方案 – Questioner