我正在写一个应用程序,每10秒得到我的坐标并发送到服务器。我有一个服务,每10秒(用AlarmManager实现)获得当前的全球定位系统坐标。但总是只显示出先得到坐标,为什么?
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;
}}
发布于 2013-12-04 12:41:23
如果这段代码是第一次执行,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();
}
}
}发布于 2013-12-04 12:48:38
要确保获得最新和准确的位置,需要实现location监听器方法。您还应该注册广播接收方,以侦听位置的更改。这里是一个博客,详细解释了这一切。它以精确性和新鲜度为基础,监听位置变化和更新位置。
https://stackoverflow.com/questions/20375586
复制相似问题