@UnstableApi
public final class SntpClient


Static utility to retrieve the device time offset using SNTP.

Based on the Android framework SntpClient.

Summary

Nested types

Callback for calls to initialize.

Constants

static final String
DEFAULT_NTP_HOST = "time.android.com"

The default NTP host address used to retrieve getElapsedRealtimeOffsetMs.

Public fields

static long
@GuardedBy(value = "valueLock")
elapsedRealtimeOffsetMs
static boolean
@GuardedBy(value = "valueLock")
isInitialized
static String
@GuardedBy(value = "valueLock")
ntpHost

Public methods

static long

Returns the offset between elapsedRealtime and the NTP server time in milliseconds, or TIME_UNSET if isInitialized returns false.

static String

Returns the NTP host address used to retrieve getElapsedRealtimeOffsetMs.

static void

Starts loading the device time offset.

static boolean

Returns whether the device time offset has already been loaded.

static void
setNtpHost(String ntpHost)

Sets the NTP host address used to retrieve getElapsedRealtimeOffsetMs.

Constants

DEFAULT_NTP_HOST

public static final String DEFAULT_NTP_HOST = "time.android.com"

The default NTP host address used to retrieve getElapsedRealtimeOffsetMs.

Public fields

elapsedRealtimeOffsetMs

@GuardedBy(value = "valueLock")
public static long elapsedRealtimeOffsetMs

isInitialized

@GuardedBy(value = "valueLock")
public static boolean isInitialized

ntpHost

@GuardedBy(value = "valueLock")
public static String ntpHost

Public methods

getElapsedRealtimeOffsetMs

public static long getElapsedRealtimeOffsetMs()

Returns the offset between elapsedRealtime and the NTP server time in milliseconds, or TIME_UNSET if isInitialized returns false.

The offset is calculated as ntpServerTime - deviceElapsedRealTime.

getNtpHost

public static String getNtpHost()

Returns the NTP host address used to retrieve getElapsedRealtimeOffsetMs.

initialize

public static void initialize(
    @Nullable Loader loader,
    @Nullable SntpClient.InitializationCallback callback
)

Starts loading the device time offset.

Parameters
@Nullable Loader loader

A Loader to use for loading the time offset, or null to create a new one.

@Nullable SntpClient.InitializationCallback callback

An optional InitializationCallback to be notified when the time offset has been initialized or initialization failed.

isInitialized

public static boolean isInitialized()

Returns whether the device time offset has already been loaded.

If false, use initialize to start the initialization.

setNtpHost

public static void setNtpHost(String ntpHost)

Sets the NTP host address used to retrieve getElapsedRealtimeOffsetMs.

The default is DEFAULT_NTP_HOST.

If the new host address is different from the previous one, the NTP client will be isInitialized uninitialized} again.

Parameters
String ntpHost

The NTP host address.