Step #4: Supporting Instant on Older Devices

However, you probably have a new red undersquiggle, this time for the now() call on Instant. If you hover your mouse over that error, you should see something to the effect of “Call requires API level 26 (current min is 21): java.time.Instant#now”.

The java.time classes were not added to Android until API Level 26 (Android 8.0). Our project’s minSdkVersion is 21 (Android 5.0). The error is pointing out that this code will crash if we try running it on an Android 5.0-7.1 device.

That does not sound good.

Fortunately, Google has added a way for us to support Instant and other java.time classes on older versions of Android. To do that, we need to make a tweak to app/build.gradle.

If you open up that file, you should see lines like these:

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

These tell the Android build tools that we are using Java 8 syntax underneath the Kotlin that we are writing.

Add a coreLibraryDesugaringEnabled true line to that compileOptions closure, giving you:

  compileOptions {
    coreLibraryDesugaringEnabled true
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

Also, in our list of dependencies, add:

  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'

This is a corresponding library used by this “desugaring” mechanism that supplies implementations of the missing logic on those older devices.

You should have another “Sync Now” banner — go ahead and sync the project with the Gradle files. After that completes, the error for now() should be gone.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.