# Play Services Time API

The Time API provides access to time signals backed by [Google Play services'](https://developers.google.com/android.md.txt) accurate time-keeping service.

This is useful if you want to know the correct UTC time, as the Android system clock can be incorrect if the user has set it manually.

Previously, you might have needed to include an NTP client in your app to get an external time from a time server. The Time API helps developers fetch more reliable time information.

The Android platform APIs provide [SystemClock.currentNetworkTimeClock()](https://developer.android.com/reference/android/os/SystemClock#currentNetworkTimeClock()), but this is only available on API level 33 and above. [TrustedTimeClient](https://developers.google.com/android/reference/com/google/android/gms/time/TrustedTimeClient.md.txt) provides alternatives and information about accuracy bounds for the returned time.

## App prerequisites

- Make sure that your app's build file uses the following values:
  - Minimum SDK version of `21` or higher.
  - Compile SDK version of `21` or higher.

## Configure your app

1. In your project-level `build.gradle` file, include [Google's Maven repository](https://maven.google.com/web/index.html) and [Maven central repository](https://mvnrepository.com/repos/central) in both your `buildscript` and `allprojects` sections:  

   ```json
     buildscript {
         repositories {
             google()
             mavenCentral()
         }
     }

     allprojects {
         repositories {
             google()
             mavenCentral()
         }
     }
     
   ```
2. Add the dependencies for the Time API to your module's app-level [Gradle](https://gradle.org/) file, normally `app/build.gradle`:  

   ```
     dependencies {
       implementation 'com.google.android.gms:play-services-time:16.0.1'
     }
     
   ```

## Initialize TrustedTime Client

The simplest way to integrate is to initialize the [TrustedTimeClient](https://developers.google.com/android/reference/com/google/android/gms/time/TrustedTime.md.txt) early in your app lifecycle. You can do this in your Application's class `onCreate()` and keep the client in your `Application` singleton. This allows you to use the client throughout your app.

```kotlin
  class MyApplication : Application() {
      var trustedTimeClient: TrustedTimeClient? = null
        private set

      override fun onCreate() {
        super.onCreate()
        val initializeTrustedTimeClientTask = TrustedTime.createClient(this)
        initializeTrustedTimeClientTask.addOnCompleteListener { task ->
          if (task.isSuccessful) {
            // Stash the client
            trustedTimeClient = task.result
          } else {
            // Handle error, maybe retry later
            val exception = initializeTrustedTimeClientTask.exception
          }
        }
        // To use Kotlin Coroutine, you can use the await() method, see
        // https://developers.google.com/android/guides/tasks#kotlin_coroutine
        // for more info.
      }
    }
  }
```

## Use TrustedTimeClient anywhere in your app

```kotlin
  // Retrieve the TrustedTimeClient from your application class
  val myApp = applicationContext as MyApplication

  // In this example, System.currentTimeMillis() is used as a fallback if the
  // client is null (i.e. client creation task failed) or when there is no time
  // signal available. You may not want to do this if using the system clock is
  // not suitable for your use case.
  val currentTimeMillis =
    myApp.trustedTimeClient?.computeCurrentUnixEpochMillis()
        ?: System.currentTimeMillis()
  // trustedTimeClient.computeCurrentInstant() can be used if you'd rather use
  // Instant instead of long for Unix epoch times and you are able to use the APIs.
```

> [!NOTE]
> **Note:** Third-party Android support libraries often allow developers to invoke
> initialization logic at application start without adding it directly to a custom
> `Application` class. The code above is an example.
>
> The TrustedTimeClient can also be obtained within short-lived components like Activity
> and Service, either during `onCreate()`, or on demand. Note that the
> `Task<TrustedTimeClient>` may not complete immediately, so developers must
> handle the delay, as shown in the example above with a null TrustedTimeClient.
>
> If you create multiple TrustedTimeClient instances, ensure you call
> `dispose()` on each instance when finished to release resources and prevent
> unnecessary listener activity. For additional information, see the
> [`dispose()`](https://developers.google.com/android/reference/com/google/android/gms/time/TrustedTimeClient.md.txt#dispose()) documentation.