Descriptive image for Page: Desugaring Android Java 8

Desugaring Android Java 8

How often do we Android developers get a warning like: “Call requires api level 26 (current min is 21)” ? Actually quite a lot. The issue with Android is that old devices were shipped with a Dalvik Virtual Machine that does not support newer language features and APIs. That can be really frustrating from time to time, because newer APIs are usually easier to use or provide nice additions to their feature sets.

Lucky for us: the Android team provides a way to get around these restrictions -> Desugaring.

Desugaring

Desugaring is done through the new D8/R8 toolchain. The compile chain applies transformations to the bytecode and rewrites it in a way that the new features we want to use get backported.

Some more information on the R8/R8 compilers can be found here:

How to use Java 8 language features

A precondition to be able to use newer language features is using the Android Gradle plugin 3.0.0 or higher.

The first step is to tell Gradle that we want to use Java 8 compatibility:

android {
  ...
  // Needed for Java 8 compatibility (in Java AND Kotlin projects)
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  // Apply Java 8 compatibility for kotlin
  kotlinOptions {
    jvmTarget = "1.8"
  }
  ...
}

This will already grant you access to:

  • Lamda expressions
  • Method references
  • Repeating annotations
  • Static and default interface methods
  • Type annotations
  • Try-with-resources

How to use Java 8 classes and APIs features

Using newer classes and APIs is not included in above approach. To enable further support your project must run with Android Gradle Plugin 4.0.0 or higher.

Enabling support is as easy as adding 2 lines to your app-level build.gradle file:

android {
  ...
  compileOptions {
      ...
      coreLibraryDesugaringEnabled true
      ...
  }
  ...
}

dependencies {
  ...
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:x.x.x'
  ...
}

This will now give you support for a lot of java.time.* classes, java.util.stream.* classes and functions and more. A full list can be found here.

Additional resources

More posts