我正在写一个应用程序,每隔10秒就会得到我的坐标并发送到服务器。 我有一个服务,每10秒(用AlarmManager实现)获得当前的GPS坐标。 但它总是只显示第一个获得协调,为什么?
public class GpsService extends Service implements LocationListener {
// flag for GPS status
boolean isGPSEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
// Declaring a Location Manager
private LocationManager locationManager;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 10 * 1; // 1 minute
@Override
public void onCreate() {
Log.i("myLogs", "onCreate");
super.onCreate();
}
@Override
public IBinder onBind(Intent arg0) {
Log.i("myLogs", "onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myLogs", "onStartCommand");
getLocation();
if(location != null) {
Log.i("myLogs", "lat = " + Double.toString(location.getLatitude()) + "lng = " + Double.toString(location.getLongitude()));
}
else
Log.i("myLogs", "no location for your today");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("myLogs", "onDestroy");
super.onDestroy();
}
public Location getLocation() {
try {
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
stopSelf();
} else {
this.canGetLocation = true;
// 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("myLogs", "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;
}
}
答案 0 :(得分:1)
如果此代码首次执行,location
为null
所以它将分配最新的位置
在第二次传递时,它不为空,因此它会跳过整个部分而不会更新location
或latitude
或longitude
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("myLogs", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
答案 1 :(得分:0)
要确保获得最新且准确的位置,您需要实现位置监听器方法。您还应注册广播接收器以收听位置变化。 Here是一篇博文,详细解释了所有这些内容。它会根据准确性和新鲜度监听位置更改并更新位置。