android - 如何获取gps位置android

标签 android gps

我正在尝试拥有一个恒定的 gps 监听器,它会每隔 x 分钟将其位置(经度和纬度坐标)发送到 Web 服务器。单击按钮时,它还会将其位置发送到网络服务器。我意识到要获得 gps 信号,您需要输入多长时间才能找到一个位置,但是我如何编写一个程序来获取 gps 位置并每隔 x 分钟发送一次坐标(即使在不在后​​台并按下按钮时也是如此) ?

//点击时

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, whatshouldIputhere?, 0, this);

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

最佳答案

我已经开始工作了:

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;
    }
}

很简单。它获得最佳可用提供者并获得其最后已知位置。
如果你只需要GPS,试试this .

希望对您有所帮助!

编辑:

试试这个:

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;
    }
}

此代码获取最后一个已知位置,然后请求实际位置。

关于android - 如何获取gps位置android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7157927/

相关文章:

android - 将我的应用移植到 Google TV 时出错

ios - EXC_BAD_INSTRUCTION 在 Swift 中对于 locationManager 崩溃(经理 : CLLocationManager, didUpdateLocations 位置:[CLLocation])

geolocation - 如何在距另一个地理点的距离 d 内创建随机地理点?

android - 在单独的类中使用 Google Play 位置 API?

java - 无法解析 MY_PERMISSION_ACCESS_COURSE_LOCATION

android - 在 Android 自定义 ROM 中修改通话中的语音播放

android - 为什么我把 if (savedInstanceState != null){} 放在 onCreate 方法中并不重要

自上次更新到版本 1.4 以来的 Android Studio 错误

android - 如何在 Android 中获取 TimeZone 的名称

Android GPS 和 wifi 状态 在应用程序中