【发布时间】:2013-12-04 12:36:52
【问题描述】:
我正在编写一个应用程序,每 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;
}
}
【问题讨论】:
-
你是否重写了LocationListener的方法,比如onLocationChanged。
-
不,我需要在里面做什么?
-
看看这篇博文android-developers.blogspot.com/2011/06/… 里面有关于刷新位置的详细解释