2

我正在使用 Google Service API、LocationServices.FusedLocationApi 来查找用户的当前位置,然后再更新位置。我已经在模拟器和实际设备上进行了测试,我发现如果我关闭 GPS LocationServices.FusedLocationApi.getLastLocation() 总是返回 null,但是如果我打开 GPS,我会得到一个有效值。这是我正在使用的代码:

private GoogleApiClient mGoogleApiClient;
private Location mLastKnownLocation;
mLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if (mLastKnownLocation != null) {
    Log.i(TAG, String.valueOf(mLastKnownLocation.getLatitude()));
    Log.i(TAG, String.valueOf(mLastKnownLocation.getLongitude()));
}

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), this);

我在这里错过了什么吗?提前致谢。

4

1 回答 1

2

我认为您应该首先使用以下方法检查您的设备是否具有 GPS:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();
        }

 private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

然后使用LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient).

有关更多信息和代码,请参阅此处

于 2015-10-15T16:54:52.290 回答