gpt4 book ai didi

android - 如何获取gps位置android

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:19:49 28 4
gpt4 key购买 nike

我正在尝试拥有一个恒定的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com