1
我嘗試用下面的公式得到Location.getTime()本地時間:GPS位置和本地時間
long localTime = location.getTime() + Calendar.getInstance().getTimeZone().getOffset(Calendar.ZONE_OFFSET);
;
但我在不同的Android版本和不同的模擬器上獲得不同的時間。我怎樣才能始終獲得正確的時間?
完整的代碼是:
private final long TimeOffset = Calendar.getInstance().getTimeZone().getOffset(Calendar.ZONE_OFFSET);
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
locationlistener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
boolean wasNull = locFine == null;
if (location.getProvider().equals(android.location.LocationManager.GPS_PROVIDER)) {
locFine = location;
//long TimeOffset = Calendar.getInstance().getTimeZone().getRawOffset();
long gpsTime = locFine.getTime() + TimeOffset;
long SystemTime = Calendar.getInstance().getTimeInMillis();
timeOffsetGPS = gpsTime - SystemTime;
Date dtgps = new Date(locFine.getTime());
Log.d("Location", "Time GPS: " + dtgps); // This is what we want!
if (context != null && a != null) {
if (wasNull) lib.ShowToast(a, getString(R.string.gotGPS));
/*
lib.ShowMessage(a,"gps time: " + dtgps
+ "\nsystem time: " + new Date(SystemTime)
+ "\noffset: " + timeOffsetGPS/1000
+ "\ncorrected gpstime: " + new Date(gpsTime));
*/
}
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
if (a != null) lib.ShowToast(context, context.getString(R.string.gpsstatus) + " " + s);
}
@Override
public void onProviderEnabled(String s) {
if (context != null) lib.ShowToast(context, s + " " + getString(R.string.enabled));
}
@Override
public void onProviderDisabled(String s) {
if (context != null)
lib.ShowMessage(context, s + " " + getString(R.string.disabled));
}
};
try {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 5, locationlistener);}
我知道location.getTime()通常會得到UTC時間,但我不需要格式化的日期,但本地時間以毫秒爲單位。當然,我可以再次解析格式化的日期以獲取當地時間,但這不會非常有效。 –
你想在當地時間做什麼?這些信息可能有助於給出更好的答案。 –
我想計算從gps到系統時間的本地時間之間的偏移量,以更正系統時間(如果需要)。 –