
Posted by Kanyinsola Fapohunda – Software program Engineer, and Geoffrey Boullanger – Technical Lead
Correct time is essential for all kinds of app functionalities, from scheduling and occasion administration to transaction logging and safety protocols. Nonetheless, a person can change the gadget’s time, so a extra correct supply of time than the gadget’s native system time could also be required. That is why we’re introducing the TrustedTime API that leverages Google’s infrastructure to ship a reliable timestamp, impartial of the gadget’s probably manipulated native time settings.
How does TrustedTime work?
The brand new API leverages Google’s safe infrastructure to supply a trusted time supply to your app. TrustedTime periodically syncs its clock to Google’s servers, which have entry to a extremely correct time supply, in order that you don’t want to make a server request each time you need to know the present community time. Moreover, we have built-in a singular mannequin that calculates the gadget’s clock drift. This can inform you when the time could also be inaccurate between community synchronizations.
Why is an correct supply of time essential?
Many apps depend on the gadget’s clock for varied options. Nonetheless, customers can change their gadget’s time settings, both deliberately or unintentionally, subsequently altering the time that your app will get. This will result in issues resembling:
- Information Inconsistency: Apps counting on chronological occasion ordering are weak to information corruption if customers manipulate gadget time. TrustedTime mitigates this danger by offering a reliable time supply.
- Safety Gaps: Time-based safety measures, like one-time passwords or timed entry controls require an unaltered time supply to be efficient.
- Unreliable Scheduling: Apps that rely on correct scheduling, like calendar or reminder apps, can malfunction if the gadget clock (i.e. Unix timestamp) is wrong.
- Inaccurate Time: The gadget’s inside clock can drift attributable to varied components, resembling temperature, doze mode, battery stage, and so forth. This will result in issues in functions that require extra precision. The TrustedTime API additionally supplies the estimated error with the timestamps, so as to guarantee your app’s time-sensitive operations are carried out appropriately.
- Lack of Consistency Between Gadgets: Inconsistent time throughout units may cause issues in multi-device situations, resembling gaming or collaborative functions. The TrustedTime API helps be certain that all units have a constant view of time, bettering the person expertise.
- Pointless Energy and Information Consumption: TrustedTime is designed to be extra environment friendly than calling an NTP server each time an app wants the present time. It avoids the overhead of repeated community requests by periodically syncing its clock with time servers. This synced time is then used as a reference level, and the TrustedTime API calculates the present time based mostly on the gadget’s inside clock. This method reduces community utilization and improves efficiency for apps that want frequent time checks.
TrustedTime Use Instances
The TrustedTime API opens up a variety of potentialities for enhancing the reliability and safety of your apps, with use instances in areas resembling:
- Monetary Purposes: Make sure the accuracy of transaction timestamps even when the gadget is offline, stopping fraud and disputes.
- Gaming: Implement honest play by stopping customers from manipulating the sport clock to achieve an unfair benefit.
- Restricted-Time Presents: Assure that promotions and provides expire on the appropriate time, whatever the person’s gadget settings.
- E-commerce: Precisely monitor order processing and supply occasions.
- Content material Licensing: Implement time-based restrictions on digital content material, like leases or subscriptions.
- IoT Gadgets: Synchronize clocks throughout a number of units for constant information logging and management.
- Productiveness apps: Precisely file the time of any modifications made to cloud paperwork whereas offline.
Getting began with the TrustedTime API
The TrustedTime API is constructed on prime of Google Play companies, making integration seamless for many Android builders.
The best technique to combine is to initialize the TrustedTimeClient early in your app lifecycle, resembling within the onCreate() technique of your Utility class. The next instance makes use of dependency injection with Hilt to make the time consumer accessible to parts all through the app.
[Optional] Setup dependency injection
// TrustedTimeClientAccessor.kt import com.google.android.gms.duties.Process import com.google.android.gms.time.TrustedTimeClient interface TrustedTimeClientAccessor { enjoyable createClient(): Process<TrustedTimeClient> } // TrustedTimeModule.kt @Module @InstallIn(SingletonComponent::class) class TrustedTimeModule { @Gives enjoyable provideTrustedTimeClientAccessor( @ApplicationContext context: Context ): TrustedTimeClientAccessor { return object : TrustedTimeClientAccessor { override enjoyable createClient(): Process<TrustedTimeClient> { return TrustedTime.createClient(context) } } } }
Initialize early in your app’s lifecycle
// TrustedTimeDemoApplication.kt @HiltAndroidApp class TrustedTimeDemoApplication : Utility() { @Inject lateinit var trustedTimeClientAccessor: TrustedTimeClientAccessor var trustedTimeClient: TrustedTimeClient? = null non-public set override enjoyable onCreate() { tremendous.onCreate() trustedTimeClientAccessor.createClient().addOnCompleteListener { process -> if (process.isSuccessful) { // Stash the consumer trustedTimeClient = process.outcome } else { // Deal with error, possibly retry later val exception = process.exception } } // To make use of Kotlin Coroutine, you should utilize the await() technique, // see https://builders.google.com/android/guides/duties#kotlin_coroutine for more information. } } NOTE: In case you do not use dependency injection in your app. You'll be able to merely name `TrustedTime.createClient(context)` as a substitute of utilizing a TrustedTimeClientAccessor.
Use TrustedTimeClient wherever in your app
// Retrieve the TrustedTimeClient out of your utility class val myApp = applicationContext as TrustedTimeDemoApplication // On this instance, System.currentTimeMillis() is used as a fallback if the // consumer is null (i.e. consumer creation process failed) or when there isn't a time // sign accessible. Chances are you'll not need to do that if utilizing the system clock is // not appropriate to your use case. val currentTimeMillis = myApp.trustedTimeClient?.computeCurrentUnixEpochMillis() ?: System.currentTimeMillis() // trustedTimeClient.computeCurrentInstant() can be utilized if Instantaneous is // most well-liked to lengthy for Unix epoch occasions and you'll be able to use the APIs.
Use in short-lived parts like Exercise
@AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var trustedTimeAccessor: TrustedTimeAccessor non-public var trustedTimeClient: TrustedTimeClient? = null override enjoyable onCreate(savedInstanceState: Bundle?) { tremendous.onCreate(savedInstanceState) ... trustedTimeAccessor.createClient().addOnCompleteListener { process -> if (process.isSuccessful) { // Stash the consumer trustedTimeClient = process.outcome } else { // Deal with error, possibly retry later or use one other time supply. val exception = process.exception } } } non-public enjoyable getCurrentTimeInMillis() : Lengthy? { return trustedTimeClient?.computeCurrentUnixEpochMillis() } }
TrustedTime API availability and limitations
The TrustedTime API is out there on all units operating Google Play companies on Android 5 (Lollipop) and above. You should add the dependency com.google.android.gms:play-services-time:16.0.1 (or above) to entry the brand new API. No further permission is required to make use of this API. Nonetheless, TrustedTime wants an web connection after the gadget begins as much as present timestamps. If the gadget hasn’t linked to the web since booting, the TrustedTime APIs will not return timestamps.
It’s essential to notice that the gadget’s inside clock can drift attributable to components like temperature, doze mode, and battery stage. TrustedTime would not forestall this drift, however its APIs present an error estimate for every timestamp. Use this estimate to find out if the timestamp’s accuracy meets your utility’s necessities. Whereas TrustedTime makes it tougher for customers to control the time accessed by your app, it doesn’t assure full security. Superior methods can nonetheless be used to tamper with the gadget’s time.
Subsequent steps
To study extra concerning the TrustedTime API, try the next sources:

