获取当前lat长的android

问题描述 投票:0回答:4

我想在Button按下获取Location对象。我知道LocationListener回调,但它们只在特定时间或距离后执行。我想立即获得位置。有没有办法这样做。

android gps location
4个回答
2
投票

欢迎您在getLastKnownLocation()上致电LocationManager,以检索您所请求的位置提供商的最后一个已知位置。然而:

  • 那个位置可能很旧
  • 那个位置可能是null

因此,您的代码需要能够应对这两种情况。


5
投票
public class GPSHelper {

    private Context context;
    // flag for GPS Status
    private boolean isGPSEnabled = false;
    // flag for network status
    private boolean isNetworkEnabled = false;
    private LocationManager locationManager;
    private Location location;
    private double latitude;
    private double longitude;

    public GPSHelper(Context context) {
        this.context = context;

        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

    }   public void getMyLocation() {
        List<String> providers = locationManager.getProviders(true);

        Location l = null;
        for (int i = 0; i < providers.size(); i++) {
            l = locationManager.getLastKnownLocation(providers.get(i));
            if (l != null)
                break;
        }
        if (l != null) {
            latitude = l.getLatitude();
            longitude = l.getLongitude();
        }
    }

    public boolean isGPSenabled() {
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        return (isGPSEnabled || isNetworkEnabled);
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        return longitude;
    }

0
投票

使用LocationManager类:

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
    latitude=location.getLatitude();
    longitude=location.getLongitude();
    Log.d("old","lat :  "+latitude);
    Log.d("old","long :  "+longitude);
    this.onLocationChanged(location);
}   

0
投票

请尝试以下方法:https://github.com/delight-im/Android-SimpleLocation

如果您的位置已启用,则只需3行代码:

SimpleLocation location = new SimpleLocation(this); //or context instead of this
double latitude = location.getLatitude();
double longitude = location.getLongitude();
© www.soinside.com 2019 - 2024. All rights reserved.