我想在位置更改时获取纬度和经度。如何使用 Intentservice?另一件事是,即使应用程序在后台,我也想要连续的当前纬度和经度。
4 回答
你可以试试getLastKnownLocation (),但是很可能会为null。并且 IntentService 不能等待某些位置修复到达。
相反,您需要一个常规服务,专门用于处理这种情况。改用cwac- locpoll
You will need to implement LocationListner in a service. Here is a link that has more information. Location Listener in Background Service Android and Location listener in a service sends notification issue
In case you dont want to use a service: BroadcastReceiver for location You need to implement a custom broadcast receiver.
尝试下面的代码它对我有用以获得坐标
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
希望也适合你
如果你真的必须使用 IntentService,你可以实现一个带有适当超时的循环。使用 onLocationChanged 更改一些值。循环可以每隔一秒测试一次这个值。如果值改变,退出循环,如果达到超时退出循环。该循环将使 IntentService 保持活动状态,等待 onLocationChanged 触发。