Android LocationManager始终返回相同的旧位置

时间:2016-03-24 14:11:11

标签: android gps locationmanager locationlistener

我的Android应用程序存在问题。我想收到位置更新并写下以下代码:

onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    requestPermission();
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this);
        // Define the criteria how to select the location provider -> use
        // default
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            onLocationChanged(location);
        }
    }

}

onLocationChanged:

@Override
public void onLocationChanged(Location location) {

    if (mMap != null) {
        setMoveToLocation(location, mMap.getCameraPosition().zoom);
    }

}

和setMoveToLocation

private void setMoveToLocation(Location location, float zoom) {
    // Add a marker at given location and move the camera
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
    Log.i("Location", "Lat: " + lat + ", Long: " + lng + " Time: " + location.getTime());
    LatLng pos = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(pos).title("Your position"));
    Log.i("Zoom", "Zoom: " + zoom);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, zoom));
}

查看输出: Log output

它始终是同一个错误的位置,我不是位于51,7! GPS肯定会打开,我会收到相关通知和其他应用程序,如谷歌地图或这里正常工作。 我使用的是带有Android 6.0的华为Honor 7。

有什么想法吗?

提前致谢, Plebo

1 个答案:

答案 0 :(得分:1)

您正在将经度和经度投射到int:

int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());

由于纬度和经度是双倍的,它们分别被铸造成51和7