Introducing a reliable approach to time keeping for your apps

Introducing a reliable approach to time keeping for your apps

Home » News » Introducing a reliable approach to time keeping for your apps
Table of Contents

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. Nevertheless, a person can change the system’s time, so a extra correct supply of time than the system’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 system’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 system’s clock drift. This may 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 system’s clock for varied options. Nevertheless, customers can change their system’s time settings, both deliberately or unintentionally, due to this fact altering the time that your app will get. This may result in issues akin to:

    • Information Inconsistency: Apps counting on chronological occasion ordering are weak to knowledge corruption if customers manipulate system 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 system clock (i.e. Unix timestamp) is inaccurate.
    • Inaccurate Time: The system’s inside clock can drift as a result of varied elements, akin to temperature, doze mode, battery stage, and many others. This may result in issues in functions that require extra precision. The TrustedTime API additionally supplies the estimated error with the timestamps, to be able to guarantee your app’s time-sensitive operations are carried out appropriately.
    • Lack of Consistency Between Units: Inconsistent time throughout gadgets may cause issues in multi-device situations, akin to gaming or collaborative functions. The TrustedTime API helps make sure that all gadgets have a constant view of time, enhancing 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 primarily based on the system’s inside clock. This strategy reduces community utilization and improves efficiency for apps that want frequent time checks.

TrustedTime Use Instances

The TrustedTime API opens up a spread of potentialities for enhancing the reliability and safety of your apps, with use instances in areas akin to:

    • Monetary Functions: Make sure the accuracy of transaction timestamps even when the system is offline, stopping fraud and disputes.
    • Gaming: Implement honest play by stopping customers from manipulating the sport clock to realize an unfair benefit.
    • Restricted-Time Provides: Assure that promotions and affords expire on the appropriate time, whatever the person’s system settings.
    • E-commerce: Precisely observe order processing and supply occasions.
    • Content material Licensing: Implement time-based restrictions on digital content material, like leases or subscriptions.
    • IoT Units: Synchronize clocks throughout a number of gadgets for constant knowledge 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 high 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, akin to 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 {
  @Offers
  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
    personal set

  override enjoyable onCreate() {
    tremendous.onCreate()
    trustedTimeClientAccessor.createClient().addOnCompleteListener { activity ->
      if (activity.isSuccessful) {
        // Stash the consumer
        trustedTimeClient = activity.end result
      } else {
        // Deal with error, possibly retry later
        val exception = activity.exception
      }
    }
    // To make use of Kotlin Coroutine, you should use the await() technique, 
    // see https://builders.google.com/android/guides/duties#kotlin_coroutine for more information.
  }
}

NOTE: If you happen to 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 activity failed) or when there isn't a time
  // sign accessible. It's possible you'll not need to do that if utilizing the system clock is
  // not appropriate on your use case.
  val currentTimeMillis =
    myApp.trustedTimeClient?.computeCurrentUnixEpochMillis()
        ?: System.currentTimeMillis()
  // trustedTimeClient.computeCurrentInstant() can be utilized if Immediate 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

   personal var trustedTimeClient: TrustedTimeClient? = null

  override enjoyable onCreate(savedInstanceState: Bundle?) {
    tremendous.onCreate(savedInstanceState)
    ...
    trustedTimeAccessor.createClient().addOnCompleteListener { activity ->
      if (activity.isSuccessful) {
          // Stash the consumer
          trustedTimeClient = activity.end result
        } else {
         // Deal with error, possibly retry later or use one other time supply.
          val exception = activity.exception
        }
    }
  }

  personal enjoyable getCurrentTimeInMillis() : Lengthy? {
    return trustedTimeClient?.computeCurrentUnixEpochMillis()
  }
}

TrustedTime API availability and limitations

The TrustedTime API is obtainable on all gadgets operating Google Play companies on Android 5 (Lollipop) and above. It’s essential to 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. Nevertheless, TrustedTime wants an web connection after the system begins as much as present timestamps. If the system hasn’t related to the web since booting, the TrustedTime APIs will not return timestamps.

It’s essential to notice that the system’s inside clock can drift as a result of elements like temperature, doze mode, and battery stage. TrustedTime would not stop 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 harder 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 system’s time.

Subsequent steps

To study extra concerning the TrustedTime API, try the next assets:

Supply hyperlink

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 
share this article.

Enjoying my articles?

Sign up to get new content delivered straight to your inbox.

Please enable JavaScript in your browser to complete this form.
Name