【发布时间】:2013-04-23 02:50:11
【问题描述】:
我想在位置更改时获取纬度和经度。如何使用 Intentservice?另一件事是即使应用程序在后台我也想要当前的纬度和经度。
【问题讨论】:
标签: android service background android-pendingintent intentservice
我想在位置更改时获取纬度和经度。如何使用 Intentservice?另一件事是即使应用程序在后台我也想要当前的纬度和经度。
【问题讨论】:
标签: android service background android-pendingintent intentservice
您可以尝试getLastKnownLocation(),但它很可能为空。并且 IntentService 不能等待某个位置修复到达。
相反,您需要一个常规服务来处理这种情况。改用cwac-locpoll
【讨论】:
试试下面的代码,它对我有用以获得坐标
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 中无法正常工作,因为在您获得位置修复之前很久,该服务就会被破坏。
您需要在服务中实现 LocationListner。这是一个包含更多信息的链接。 Location Listener in Background Service Android 和 Location listener in a service sends notification issue
如果您不想使用服务: BroadcastReceiver for location 您需要实现自定义广播接收器。
【讨论】:
如果你真的必须使用 IntentService,你可以实现一个带有适当超时的循环。使用 onLocationChanged 更改一些值。 循环可以每隔一秒测试一次这个值。如果值改变,退出循环,如果达到超时退出循环。 该循环将使 IntentService 保持活动状态,等待 onLocationChanged 触发。
【讨论】: