如何获得gps定位android

Sea*_*ean 9 gps android

我试图有一个恒定的gps监听器,每隔x分钟将其位置(长和lat坐标)发送到Web服务器.在按钮上单击它还会将其位置发送到Web服务器.我知道要获取gps信号,你可以输入寻找位置的频率,但是如何编写一个程序可以获得gps位置并每x分钟发送一次坐标(即使在背景中也没有按下按钮) ?

//在点击中

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, whatshouldIputhere?, 0, this);
Run Code Online (Sandbox Code Playgroud)

public void onLocationChanged(Location location) {
    if (location != null) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
    }
}
Run Code Online (Sandbox Code Playgroud)

and*_*i90 18

我有这个工作:

private void _getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) 
            getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}
Run Code Online (Sandbox Code Playgroud)

这很简单.它获得了最佳可用提供商并获得其最后的已知位置.
如果您只想使用GPS,请试试这个.

希望能帮助到你!

编辑:

试试这个:

private void _getLocation() {
    // Get the location manager
    LocationManager locationManager = (LocationManager) 
            getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    LocationListener loc_listener = new LocationListener() {

        public void onLocationChanged(Location l) {}

        public void onProviderEnabled(String p) {}

        public void onProviderDisabled(String p) {}

        public void onStatusChanged(String p, int status, Bundle extras) {}
    };
    locationManager
            .requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码获取最后的已知位置,然后请求实际位置.