Retrieving GPS Time on Android Devices

Android devices can obtain accurate time for their current time zone through two primary methods:

Method 1: Time Synchronization via Wi-Fi

When the device is connected to a network and has Automatic date & time and Automatic time zone enabled in system settings, the system automatically updates to the correct time. Components like TextClock and DateClock will also reflect these updates automatically.

Method 2: Time Retrieval via GPS

2.1 Using Native Location Services

In scenarios where no network connection is available but GPS is functional, you can obtain the local time by accessing raw location data. Implementation detail are provided below:

Note: The following code is implemented within a Fragment.

/**
 * Manager for handling location services
 */
private LocationManager locationService;
/**
 * Timeout duration for canceling background location updates (5 minutes)
 */
private static final int LOCATION_TIMEOUT_MS = 5 * 60 * 1000;
/**
 * Flag to prevent multiple cancellation attempts
 */
private boolean locationUpdatesCancelled = false;

/**
 * Initializes system time using GPS when network is unavailable.
 * If network is available, system time should update automatically.
 */
private void initializeSystemTime() {
    if (!NetworkUtils.isNetworkAvailable(getContext())) {
        startLocationUpdates();
        // Use Handler.postDelayed() for standard implementation
        ArchTaskExecutor.getInstance().postToMainThreadDelayed(
            cancelLocationTask, LOCATION_TIMEOUT_MS
        );
    }
}

// Note: Regular apps require location permissions; system apps may bypass this requirement
@SuppressLint("MissingPermission")
private void startLocationUpdates() {
    Log.i("GPS", "Starting GPS location updates without network");
    locationService = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    locationService.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 0, 0, locationCallback
    );
}

/**
 * Callback for receiving location updates with GPS time
 */
private final LocationListener locationCallback = location -> {
    if (location != null) {
        long gpsTimestamp = location.getTime();
        stopLocationUpdates();
        Log.i("GPS", "GPS time obtained: " + gpsTimestamp);
        // Test with: updateSystemTime(1712800932000L); // Should display 2024-04-11 10:02:12
        updateSystemTime(gpsTimestamp);
    }
};

private final Runnable cancelLocationTask = () -> {
    Log.i("GPS", "Location update timeout, stopping updates");
    stopLocationUpdates();
};

/**
 * Stops location updates and cleans up resources
 */
public void stopLocationUpdates() {
    Log.i("GPS", "Stopping location updates: " + locationUpdatesCancelled);
    if (locationService != null && !locationUpdatesCancelled) {
        locationService.removeUpdates(locationCallback);
        locationUpdatesCancelled = true;
        locationService = null;
    }
}

/**
 * Note: System apps require <uses-permission android:name="android.permission.SET_TIME"/>
 * Regular apps can only read this value but cannot modify system time.
 */
@SuppressLint("MissingPermission")
private void updateSystemTime(long utcMillis) {
    try {
        Date gpsTime = new Date(utcMillis);
        long localMillis = gpsTime.getTime();

        AlarmManager timeManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        if (timeManager != null) {
            timeManager.setTime(localMillis);
            Log.i("GPS", "System time updated successfully: " + localMillis);
        }
    } catch (Exception e) {
        Log.e("GPS", "Failed to update system time", e);
    }
}

2.2 Using AMap SDK for Time Retrieval

If you have integrated the AMap (Gaode Maps) SDK, you can also obtain local time using their API:

/**
 * Retrieves GPS time using AMap location services
 */
@SuppressLint("MissingPermission")
public void fetchTimeViaAMap() throws Exception {
    // Initialize AMap location client
    AMapLocationClient mapClient = new AMapLocationClient(getContext());
    AMapLocationClientOption locationOptions = new AMapLocationClientOption();
    
    mapClient.setLocationListener(new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (location != null) {
                if (location.getErrorCode() == 0) {
                    // Successfully obtained location
                    int locationSource = location.getLocationType();
                    
                    SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date locationDate = new Date(location.getTime());
                    String formattedTime = timeFormatter.format(locationDate);
                    
                    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM月dd日");
                    SimpleDateFormat timeFormatter12hr = new SimpleDateFormat("HH:mm aa");
                    
                    mapClient.stopLocation();
                    
                    // Requires SET_TIME permission for system apps
                    updateSystemTime(location.getTime());
                } else {
                    Log.e("AMap", "Location error - Code: " + location.getErrorCode() 
                        + ", Info: " + location.getErrorInfo());
                }
            }
        }
    });
    
    // Configure high-accuracy location mode
    locationOptions.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
    locationOptions.setInterval(1000);
    mapClient.setLocationOption(locationOptions);
    mapClient.startLocation();
}

Important Considerations

GPS preloading is not the optimal solution for time accuracy on Android. While GPS provides precise time and location data, most scenarios don't require GPS for time synchronization. Android devices typically synchronize time automatically through network providers (cellular or Wi-Fi connections) via network time protocol. If your custom launcher displays incorrect time, the issue likely stems from network time synchronization settings rather than time zone configuration.

Implementation Notes

  • Regular applications require appropriate location permissions
  • System time modification requires the SET_TIME permission (typically restricted to system apps)
  • Network-based time synchronization should be preferred when available
  • GPS-based time retrieval is most useful in offline scenarios with GPS availability

Tags: Android GPS Time Synchronization Location Services System Time

Posted on Wed, 13 May 2026 09:13:02 +0000 by TomT