AndroidNJava8java.time

Android N Java8 java.time

我更新到最新的AndroidN sdk。我唯一不明白的是为什么我不能将 java.time 导入到我的代码中?我还以为Java8可以通过AndroidN获取呢,那为什么Google不加java.time包呢?

Android N 不支持 Java 8 的所有功能。 仅支持以下功能:

  • 默认和静态接口方法
  • Lambda 表达式
  • 可重复注释

反射和语言相关的 API:

  • java.lang.FunctionalInterface
  • java.lang.annotation.Repeatable
  • java.lang.reflect.Method.isDefault()

与可重复注解关联的反射API,例如 AnnotatedElement.getAnnotationsByType(Class)

实用程序 API:

  • java.util.function

有关更多信息,请查看以下内容 link:http://developer.android.com/preview/j8-jack.html

Android 有 java.time 个 API 的反向移植库可供使用

https://github.com/JakeWharton/ThreeTenABP

java.time 包仅在 API 26 (Android O) 中添加: https://developer.android.com/reference/java/time/package-summary.html

更新

但是,从 4.0 版开始 Android Studio 允许使用 java.time API 的子集(以及其他一些 Java 8 语言 APIs),无需 要求您的应用达到最低 API 级别:
https://developer.android.com/studio/preview/features#j8-desugar

The following set of APIs is supported in this release:

  • Sequential streams (java.util.stream)
  • A subset of java.time
  • java.util.function
  • Recent additions to java.util.{Map,Collection,Comparator}
  • Optionals (java.util.Optional, java.util.OptionalInt and java.util.OptionalDouble) and some other new classes useful with the above APIs
  • Some additions to java.util.concurrent.atomic (new methods on AtomicInteger, AtomicLong and AtomicReference)
  • ConcurrentHashMap (with bug fixes for Android 5.0)

要启用对这些语言 API 的支持,需要在 build.gradle 文件中包含以下行:

android {
  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

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

从Android Gradle插件4.0.0开始,我们终于可以放心(几乎)使用正确的java.time包类了: https://developer.android.com/studio/write/java8-support

Optional, java.time, streams,还有更多被 Android Gradle 插件脱糖成 Java 7。

要添加那些 类 支持,您只需在构建文件中添加几行:

android {
  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

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

完整列表如下:https://developer.android.com/studio/write/java8-support-table