我使用这些代码来获取位置
但是有时候我无法获得建筑物内的位置,并且那时WIFI已连接,位置已启用。
如何确保getLastKnownLocation在能够获取位置时返回位置?
LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location==null)
{
Toast.makeText(getApplicationContext(),"no location", Toast.LENGTH_SHORT).show();
return;
}
答案 0 :(得分:1)
这对我有用......
public void updateLoction(View view){
locationManger = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManger.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
txtLat.setText("" + location.getLatitude());
txtLon.setText("" + location.getLongitude());
}
locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
private void setLocation(Location location) {
if (location != null) {
txtLat.setText("" + location.getLatitude());
txtLon.setText("" + location.getLongitude());
}
locationManger.removeUpdates(this);
}