Exploring the TrustedTime API, Reliable Time in Android

Image of the author

Germán Bustamante @germanbustamante

Trusted time API logo

Introducing the TrustedTime API

Time is crucial in many apps, but what happens if the user changes their device’s time? Problems! Inconsistent data, security failures…

That’s why Google created the TrustedTime API, a solution that leverages its infrastructure to provide us with reliable timestamps.

How Does It Work? ⚙️

TrustedTime synchronizes with Google’s time servers, so you’ll always have the most accurate time! It also calculates the device clock drift, which allows us to evaluate the precision of the timestamp.

What Is It Used For?

This API is great for:

How to Get Started?

It’s very easy to integrate TrustedTime into your Android apps:

  1. Add the dependency: com.google.android.gms:play-services-time:16.0.1 (or higher) in your build.gradle file.
  2. Initialize TrustedTimeClient: Do it at the beginning of your app’s lifecycle (for example, in the onCreate() method of your Application class).

Code Example ⌨️

class MainActivity : AppCompatActivity() {

    private var trustedTimeClient: TrustedTimeClient? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        //....
        TrustedTime.createClient(this).addOnSuccessListener {
            trustedTimeClient = it
        }.addOnFailureListener {
            Log.e("MainActivity", "Failed to create TrustedTimeClient", it)
        }

        Log.i("MainActivity", "Current time in millis: ${getCurrentTimeInMillis()}")
    }

    private fun getCurrentTimeInMillis(): Long =
        trustedTimeClient?.computeCurrentUnixEpochMillis() ?: System.currentTimeMillis() //Use System.currentTimeMillis() as failsafe
}

Going Into More Detail ⏱️

The createClient() method returns a TrustedTimeClient object. This object is the key to accessing TrustedTime functionalities. You can get more information about TrustedTimeClient and its methods here.

The methods of this class provide time information in various forms: