查找当前位置

时间:2019-04-19 17:02:34

标签: java android

我找不到当前位置,总是找到我的最后一个位置。

我必须改变什么。

请帮助。

我在学校的项目作业

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gpstxt = (TextView) findViewById(R.id.txtgps);
    buttonGPS = (Button) findViewById(R.id.gpsbtn);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    final Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);

    buttonGPS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onLocationChanged(location);
        }
    });

}

private void onLocationChanged(Location location) {
    double longtitude = location.getLongitude();
    double latitude = location.getLatitude();
    gpstxt.setText("Enlem:" + latitude + "\n" + "Boylam:" + longtitude);
}

}

不是最后一个位置输出。 我想使用gps查找当前位置。

2 个答案:

答案 0 :(得分:0)

您不应使用locationManager.getLastKnownLocation()

相反,您应该订阅位置更新。

您可以查看有关实施的更多详细信息。

https://developer.android.com/training/location/receive-location-updates

答案 1 :(得分:0)

您似乎正在使用getLastKnownLocation()方法,该方法为您提供了用户的最后已知位置。

相反,您应该使用locationManager软件包中提供的requestLocationUpdates()方法。

类似的东西应该可以工作:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

参考:https://developer.android.com/guide/topics/location/strategies.html