我已经注册了我的位置管理器(LocationManager)以便每10秒更新位置信息。
mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, 50, this);
但是
onLocationChanged
回调每10秒返回一次位置,这个位置已经超过2小时了。时间戳从未改变。问题在于:2小时前我在完全不同的地方(家里)使用设备上的wifi。现在我在另一个地方(办公室)使用不同的wifi,我的应用程序显示我的当前位置为家。昨天在家时也出现了同样的情况,当时它将我的当前位置显示为办公室。当我关闭我的应用程序,打开FourSquare应用程序并重新打开我的应用程序时,它开始工作(开始显示正确的位置)。
完整代码:
public class LocationService extends Service implements LocationListener {
public static double curLat = 0.0;
public static double curLng = 0.0;
private LocationManager mgr;
private String best;
private Location location;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
best = LocationManager.NETWORK_PROVIDER;
location = mgr.getLastKnownLocation(best);
if (location != null) {
dumpLocation(location);
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10 * 1000, 50, this);
}
return START_NOT_STICKY;
}
}
private void dumpLocation(Location l) {
SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy:hh:mm:ss",
Locale.ENGLISH);
String format = s.format(l.getTime());
//The above time is always 28/03/2013:09:26:41 which is more than 2 hrs old
curLat = l.getLatitude();
curLng = l.getLongitude();
}
@Override
public void onLocationChanged(Location location) {
dumpLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
这样在Activity中启动:
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, LocationService.class);
pi = PendingIntent.getService(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 10000, pi);
清单文件中的权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
我现在可以通过打开其他基于位置的应用程序(如地图、导航器、Foursquare等)来获取正确的位置。但是为什么我的应用程序无法从提供者那里获得新的/新鲜的定位呢?谢谢。
mgr.getLastKnownLocation(best);
,requestLocationUpdates
也应该提供新的位置,对吧?建议先使用mgr.getLastKnownLocation(best);
开始,然后再注册更新。据我所知。 - Archie.bpgcmgr.getLastKnownLocation(best)
。我正在使用错误/禁用的提供程序来请求更新。再次感谢。 - Archie.bpgc