在启动时使用 LocationListener 启动的服务然后将位置和设备数据发送到 Web 服务。当不是服务的一部分时,该代码可以完美运行,该服务仅通过第一个位置并且未更新。
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
item.LatitudePhone = f_latitude;
item.LongitudePhone = f_longitude;
} else {
item.LatitudePhone = f_latitude;
item.LongitudePhone = f_longitude;
}
item.Active = false;
return item;
}
/* Request updates at startup */
// @Override
protected void onResume() {
// super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the location listener updates when Activity is paused */
// @Override
protected void onPause() {
// super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
f_latitude = (float) (location.getLatitude());
f_longitude = (float) (location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}