2

我已经在其他线程中阅读了这个问题的解决方案,但我似乎不明白为什么它返回 null。我使用了谷歌开发者网站中提供的相同片段:https ://developer.android.com/training/location/retrieve-current.html

我在我的活动中使用以下代码来获取用户的当前位置:

public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buildGoogleApiClient();
}
@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();
}
@Override
public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
}

}

如果“mLastLocation”始终为空,我们如何编写代码来获取用户的当前位置?

4

3 回答 3

1

文档状态(在文章底部):

在极少数情况下,当位置不可用时,返回的位置对象可能为空。

当设备禁用定位服务或设备处于飞行模式时,可能会发生这种情况。当长时间未请求位置时,似乎也会发生这种情况。

于 2015-10-06T15:35:42.430 回答
1

您可能需要检查您正在使用的设备的位置设置。我有同样的问题。我的位置设置设置为仅使用 gps,我将其切换为使用 wifi、gps 和移动服务来确定您的位置的高精度。这为我解决了这个问题。希望能帮助到你

于 2015-11-24T10:32:54.567 回答
0

阅读此解决方案:

    private static GoogleApiClient mGoogleApiClient;
    Location currentLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
于 2015-10-06T15:29:19.027 回答