(Android) 如何使用 Google Play 服务检索当前位置

(Android) How to retrieve current location using Google Play Services

我是 Android 应用程序开发的新手,我目前正在研究使用 Google Play 服务[=检索用户的当前位置(坐标和城市) 15=]。截至目前,我找不到任何清晰的分步教程。 任何建议或指导将不胜感激!

您可以使用 fused location provider APIs in the Google Play Service library to retrieve the device's last known location:

 Location lastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

    if (lastLocation != null) {
        double latitude = lastLocation.getLatitude();
        double longitude = lastLocation.getLongitude();

//Once you get the coordinates, you can retrieve the city name using the Geocoder class:

        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
            addresses = gcd.getFromLocation(latitude, longitude, 1);
            if (addresses != null) {
                if (addresses.size() > 0)
                    String cityName = addresses.get(0).getLocality();

            }

         }

在您的清单中:

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

这里a detailed tutorial可以帮助你

当前位置 = 最后位置

这就是 Google Android 文档中关于使用 FusedLocationProvider

获取当前位置的内容

In most cases, you are interested in the user's current location, which is usually equivalent to the last known location of the device.

如何做到这一点?

可以用这个方法

public void getCurrentLocation() {

      FusedLocationProviderClient locationProviderClient = LocationServices.
                                           getFusedLocationProviderClient(this);


     locationProviderClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {

                  @Override
                  public void onSuccess(Location location) {

                     Log.d("Location",currentLocation.toString());
                 
                  }
             });

      }

}

您需要添加<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
上面的代码是简化版。如果您的应用在 Android Lollipop 及更高版本上运行,那么您需要请求 Location permission at runtime ALSO.

你可以看到完整的代码HERE

最新的google播放服务无需连接GoogleApiClient,可直接请求位置更新。

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(20 * 1000);
mFusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {

            }
        };