Android 连接到WiFi时getLastLocation返回null

Android 连接到WiFi时getLastLocation返回null,android,location,Android,Location,全部, 我有以下问题。以下是代码摘录: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.main_radar ); int res = GooglePlayServicesUtil.isGooglePlayServicesAvailable( getApplication

全部,

我有以下问题。以下是代码摘录:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main_radar );
    int res = GooglePlayServicesUtil.isGooglePlayServicesAvailable( getApplicationContext() );
    if( res != ConnectionResult.SUCCESS )
    {
        if( BuildConfig.DEBUG )
            Log.i( "Radar", "Check failed!" );
        return;
    }
    if( servicesConnected() )
    {
        client = new LocationClient( this, this, this );
    }
    else
        return;
}

@Override
protected void onStart()
{
    super.onStart();
    if( client != null )
        client.connect();
}

@Override
public void onConnected(Bundle arg0)
{
    currLocation = client.getLastLocation();
    device.setLatitude( currLocation.getLatitude() );
    device.setLongtitude( currLocation.getLongitude() );
}
最初,我在连接4G信号时尝试运行此代码,并立即从getLastLocation()调用中收到位置信息。然而,昨天我尝试连接到我的局域网WiFi。程序崩溃了

尝试进行调查时,我发现对getLastLocation()的调用返回null。然而,连接是成功的

现在,我的问题是:我知道getLastLocation()几乎立即返回位置可能是一个好运气,而我在WiFi连接上的测试揭示了代码中的一个bug。但解决这个问题的最佳方法是什么

人们似乎建议使用位置更新。我不是在开发某种地图应用程序。我一开始就需要这个,就这样

那么,获取位置更新是最好的方法吗?它能在启用WiFi的情况下工作吗?获取位置的通常时间框架是什么?如果我将等待更新的时间设置得太少,我可能不会收到任何更新

或者根据定义它不应该起作用

谁能在这里点些灯吗


提前感谢您提供的任何提示/要点。

GetLastLocation如果尚未找到位置,则可以返回null。你必须考虑到这种可能性。如果您不想在某个位置存在之前运行代码,请请求位置更新。@Gabeschen,这不是我不想要的。我在问最好的方法。除此之外,如果我为位置更新选择的时间太短怎么办?或者使用AsyncTask检查非空值?这样,如果还没有位置,我可以显示“进度”对话框…@Igor您可以订阅LocationListener以获取位置更新,然后在第一个位置到达时取消订阅。如果用户在其设备上启用了Google定位服务,则可以通过Wifi访问。@Igor,您不需要任何类型的异步任务。启动应用程序->显示等待对话框->订阅更新。第一次更新到达->隐藏对话框->取消订阅LocationListener。@Salayou,有没有建议设置等待它到来的时间?我知道这取决于很多事情,但是。。。。