为什么 getLastKnownLocation return 旧位置?

Why getLastKnownLocation return old Location?

我尝试在我的位置上创建一个标记,但 Google 地图显示旧位置。

MapsActivity.java

private void setUpMap() {

    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
    mMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);

    Location myLocation = locationManager.getLastKnownLocation(provider);
      mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    double latitude = myLocation.getLatitude();
    double longitude = myLocation.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("I am here!").snippet("Bla bla bla"));

}

明确许可

  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
 <uses-permission android:name="myapp.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

来自 getLastKnownLocation()

的 Android 参考手册

Returns a Location indicating the data from the last known location fix obtained from the given provider.

This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

对于您的情况,您可以尝试在 Criteria 中定义准确性。

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);

一般来说,我会使用推荐的 Fused Location Provider API。您可以找到指南 here.