为什么 Android 有时无法获取位置

Why Android cannot get location sometime

我使用这些代码来获取位置

但有时无法获取建筑物内的位置,此时WIFI已连接,位置已启用。

如何确保 getLastKnownLocation 在能够获取位置时 return 定位?

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;
}

这对我有用...

    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);
}