在网上搜索,还不清楚Android开发是否支持Java 8。

在我下载/安装Java 8之前,能不能有人给我指出任何“官方”文档,说Java 8是或不支持Android开发。


当前回答

更新2020/01/17

Android Studio 4.0支持使用大量的Java 8语言API,通过使用称为desugaring的技术,而不需要为你的应用程序设置最低的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) To support these language APIs, D8 compiles a separate library DEX file that contains an implementation of the missing APIs and includes it in your app. The desugaring process rewrites your app’s code to instead use this library at runtime. To enable support for these language APIs, include the following in your module’s build.gradle file: 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' }


2017年原创文章

Android Studio 3.0开始提供对Java 8语言特性的内置支持,包括:

Lambda表达式 方法引用 类型注释(信息在编译时可用,但在运行时不可用) 重复注释 默认和静态接口方法

同样,从API级别24开始,可以使用以下Java 8 API:

java.util.stream java.util.function java.lang.FunctionalInterface java.lang.annotation.Repeatable java.lang.reflect.AnnotatedElement.getAnnotationsByType(类) java.lang.reflect.Method.isDefault ()

除此之外,try-with-resources支持扩展到所有Android API级别。

更多的Java 8特性将在未来被添加。

要开始使用受支持的Java 8语言特性,请更新Android 插件到3.0.0-alpha1(或更高版本),并将以下内容添加到您的 模块的构建。gradle文件: android { ... compileOptions { sourceCompatibility JavaVersion。VERSION_1_8 targetCompatibility JavaVersion。VERSION_1_8 } }

详情请浏览: https://developer.android.com/studio/write/java8-support.html

其他回答

是的,你可以在Android Studio中使用Java 8语言功能,但版本必须是3.0或更高。阅读这篇文章,了解如何在android studio中使用java 8特性。

https://bijay-budhathoki.blogspot.com/2020/01/use-java-8-language-features-in-android-studio.html

简单的方法

你可以为android项目启用java 1.8支持。

开放式项目结构 按Ctrl + Shift + Alt + S 或文件>项目结构 如图所示,在项目结构对话框中将Source Compatibility和Target Compatibility更新为1.8(单击File > Project Structure)。

或者你可以使用gradle

 android {
   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }

同步项目。就是这样!

注意:Java 1.8支持可用于Android Studio 3.0.0或更高版本。有关进一步阅读,请参阅文档。

我在Stack Overflow上对一个类似的问题写了一个类似的答案,但这里是答案的一部分。

Android Studio 2.1:

新版Android Studio(2.1)支持Java 8特性。以下是Android开发者博客文章的摘录:

... Android Studio 2.1版本包括对新的Jack编译器的支持和对Java 8的支持。 ... 在使用N Developer Preview进行开发时,要使用Java 8语言特性,您需要使用Jack编译器。新建项目向导[文件→新建→项目]为目标N的项目生成正确的配置。


在Android Studio 2.1之前:

Android还不支持Java 1.8(它只支持1.7),所以你不能使用Java 8的特性,比如lambdas。

这个答案提供了更多关于Android Studio兼容性的细节;州:

如果你想在Android中使用lambdas (Java 8的主要特性之一),你可以使用gradle-retrolamba

如果您想了解更多关于使用gradle-retrolambda的知识,这个答案提供了很多细节。

你确实可以使用gradle-retrolamba gradle build dependency来使用Java 8 for Android Development。

下面是我最近在Android开发中运行lambda表达式的完整指南。本指南的原始来源在最后被提到。

In this guide, a method for bringing some Java 8 features into Android Development Tools will be demonstrated, specifically aiming at Eclipse IDE. However, steps which will be described throughout this guide might also be adapted to Google’s new uprising development environment, Android Studio. It is based on the community edition of popular IntelliJ Idea IDE by JetBrains and it has recently been upgraded to its ‘beta’ version by Google in early July 2014, slightly before this guide was written. Eclipse will remain as the prominent development environment, at least for a while, and considering the fact that most Android projects have been developed using Eclipse, a method for bringing new Java 8 features like lambda expressions into ADT seems to be quite useful for developers. Android Development is based on a custom Java implementation called Apache Harmony Project which was terminated back in 2011. The most commonly used Java syntax in Android Development is Java 6 (v1.6) and Java 7 (v1.7) is also partially supported on the KitKat edition (Android 4.4.+). Therefore, Java 8 features like lambda expressions cannot be used directly in the Android App Development without applying some tweaks into the development tools. Luckily, these constructs are basically some ‘syntactic sugar’ enhancements which give developers the shortcomings of things like ‘anonymous classes’ and they can be translated into Java 6 or Java 7 classes. A recent approach for translating a Java 8 source code into lower Java versions is called RetroLambda. This library makes developers run Java 8 code with lambda expressions on Java 7 or even lower. Unfortunately, Java 8 features other than lambda expressions are not supported by RetroLambda for now but the concept of lambda expressions is the biggest leap on Java 8 platform and it’s a great tool for Android developers anyway. Details about this library can be found on its GitHub page: https://github.com/orfjackal/retrolambda#getting-started Also, a Gradle plugin for RetroLambda created by another developer allows Gradle-based builds to be implemented in Java or Android Projects. However, the developer only mentions about integrating this plugin into Android Studio environment. Details can be found on its GitHub page: https://github.com/evant/gradle-retrolambda Using these infrastructures within an Eclipse-based development environment cannot be approached directly but it’s doable and will be demonstrated throughout this guide.

准备

本指南假定读者对Android开发有基本的了解,并且基于ADT版本22.6.2,因为最近的ADT版本23.0.2似乎有布局文件夹创建等问题。有关此问题的详情可于以下连结找到:

http://code.google.com/p/android/issues/detail?id=72591

本指南中的步骤将适用于Windows 8.1 64位开发机器,但它们可以很容易地适应其他平台。新的构建系统Gradle将用于构建/清理过程,并将提供其安装程序。另外,JDK 8和JDK 7必须在开发机器上共存。安装它们必须遵循以下步骤:

Go to JDK 8 early access preview page http://jdk8.java.net Download JDK 8u20 and install it. JRE 8 installation is not necessary and it can be skipped Go to JDK 7 latest stable release page http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html Download JDK 7u65 and install it. JRE 7 installation is again not necessary and it can be skipped Add JDK 8 home folder and JDK 8 bin folder to your %PATH% variable Create a new environment variable JAVA_HOME with the value of the path of JDK 8 home folder Create a new environment variable JAVA8_HOME again with the value of the path of JDK 8 home folder Create a new environment variable JAVA7_HOME with the value of the path of JDK 7 home folder Open a terminal window and run java -version command and verify that Java 8 is up and running Run javac -version command in the same window and verify that JDK 8 Java compiler is also up and running

ADT-22.6.2必须从以下连结下载:

http://dl.google.com/android/adt/22.6.2/adt-bundle-windows-x86_64-20140321.zip

Download ADT and unzip its contents into a folder, e.g. D:\adt Define a new environment variable called ANDROID_HOME with the value of the path of your ADT installation folder, e.g. D:\adt\sdk Add your Android SDK Platform Tools and Android SDK Tools folders, e.g. D:\adt\sdk\tools and D:\adt\sdk\platform-tools, to your %PATH% variable Create a shortcut to Eclipse IDE if you like. It is located under your ADT installation folder, e.g. D:\adt\eclipse Run Eclipse IDE and create a workspace, e.g. D:\adt\workspace Click on the Android SDK Manager button which is located on the toolbar Select Android SDK Build tools Rev. 19.1 and Android Support Library only. Un-select everything else and install these two packages.

如果一切顺利,ADT将开始运行。

同时,强烈建议安装以下工具:

Eclipse Kepler Java 8 Support: It makes Eclipse recognize new Java 8 syntax extensions and makes you get rid of annoying red dots in your Java code editor. It might be installed through Help -> Install New Software in Eclipse. Enter http://download.eclipse.org/eclipse/updates/4.3-P-builds/ into the Work with field and continue to install it. Nodeclipse/Enide Gradle: It is mainly used to highlight Groovy language keywords. Groovy is used as the DSL for Gradle build scripts. This plugin can be installed through Eclipse Marketplace. However, Eclipse within ADT-22.6.2 does not come along with Eclipse Marketplace Client. Therefore, you will first need to install Eclipse Marketplace Client by means of Install New Software tool in Eclipse. Enter http//:download.eclipse.org/mpc/kepler/ into the Work with field and continue to install it. After installing Eclipse Marketplace Client, you may search for Nodeclipse/Enide Gradle in the Eclipse Marketplace Client and install it. Genymotion Virtual Device: It is a great replacement of the default Android Virtual Device which comes along with ADT. AVD is annoyingly cumbersome and it keeps on crashing for no reason. Genymotion makes you prepare Android VD's using CyanogenMod images which are executed by Oracle VirtualBox. Its single user license is for free and it can be downloaded from http://www.genymotion.com. Only a login is required and it can also be integrated into Eclipse. Details can be found under:

https://cloud.genymotion.com/page/doc/#collapse8

下图是基于Android 4.3的CyanogenMod虚拟设备的截图,

它可以被认为是一个完全成熟的Android设备,运行在基于x86或x64的个人电脑上。为了在这个虚拟设备上使用谷歌服务(如谷歌PlayStore),它使用的Android版本的gapps映像必须闪到设备上。合适的gapps图像可以从CyanogenMod网站下载:

http://wiki.cyanogenmod.org/w/Google_Apps

Gradle安装是可选的,因为它也是由Android SDK本身提供的,但强烈建议单独安装。它的安装可以按照以下步骤进行:

Go to Gradle web site: http://www.gradle.org/ Click Downloads Under Previous Releases choose version 1.10 and download either gradle-1.10-all.zip or gradle-1.10-bin.zip Unzip its contents into a folder, e.g. D:\adt\gradle Define a new environment variable called GRADLE_HOME with the value of the path of your Gradle installation folder, e.g. D:\adt\gradle Add your Gradle binaries folder, e.g. D:\adt\gradle\bin, to your %PATH% variable Open a terminal window and run gradle -v command and verify that it`s up and running If you have come up to this point successfully then it means that you are ready to create your first Android App using Java 8 features.

演示应用程序

将创建一个简单的应用程序来演示前一节中描述的工具的使用。 你可以简单地按照下面给出的步骤来深入了解在Android开发工具中使用lambda表达式:

运行Eclipse IDE,通过选择“File -> new -> Other -> Android -> Android Application Project”新建一个Android应用程序 填写如下所示的表格:

Simply click the Next button on the following forms and click the Finish button on the last one. Wait till ADT finishes loading up the project Right-click on the project and select New -> Folder and name it builders Right-click on the gen (Generated Java Files) folder and delete it. Gradle will generate the same files for us soon and we will add them into the projects build path. The gen` folder created by the default Ant builder is no longer needed and the artifacts under that folder will be obsolete Create following batch files under the builders folder: - gradle_build.cmd - gradle_post_build.cmd - gradle_clean.cmd Fill in these batch files as follows:

gradle_build.cmd:

gradle_post_build.cmd:

gradle_clean.cmd:

取消选择项目->自动生成菜单选项 右键单击项目,选择属性->生成器,取消选择ADT提供的所有默认生成器 在同一窗口中单击New按钮,选择Program,然后单击OK 将出现新的构建器配置窗口。按如下方式填写其选项卡:

新的生成器配置的主选项卡

新的生成器配置的刷新选项卡

新生成器配置的环境选项卡

新建生成器配置的“构建选项”选项卡

Create the second builder called Gradle_Post_Build that uses gradle_post_build.cmd as its program. All other settings of this builder must exactly be the same with the previously created builder. This builder will be responsible for copying the artifacts created by the build process into the bin folder. Create the third builder called Gradle_Cleaner that uses gradle_clean.cmd as its program. Only Run the builder setting in the final tab must be set as During a Clean. All other settings of this builder must exactly be the same with the first builder. This builder will be responsible for cleaning the artifacts created by the build process as the name suggests.

HelloLambda项目的新建设者

右键单击项目并选择Export 选择“Android -> Generate Gradle Build Files”,单击“Next” 在下一个窗口中选择项目并单击Finish 转到项目的根文件夹,删除gradlew和gradlew.bat文件。同时删除gradle文件夹 切换回Eclipse并选择Project -> Clean菜单选项。填写如下所示的表格:

清洁项目窗口

单击“确定”,等待清洗过程完成 在MainActivity类的setContentView函数调用之后添加如下的Java代码片段:

更改构建的开始。gradle文件直到sourceCompatibility部分,如下所示:

右键单击项目,选择属性-> Java编译器选项,并将所有遵从级别设置为Java 8。这将使Eclipse识别新的Java 8结构,如lambda表达式。 在通知窗口单击“否” 右键单击项目并选择Build project。Eclipse将开始构建项目。

构建过程

右键单击项目,进入属性-> Java构建路径。将以下文件夹添加到构建路径(如下图所示): 建立源\ buildConfig \ \调试 建立源\ r \ \调试

Eclipse现在能够识别R.java和buildConfig.java文件,并且不会显示任何表示与项目资源文件相关的错误的红点。

通过右键单击项目,然后选择Run As -> Run Configurations,为您的Android目标平台创建一个新的运行配置。例如,这个演示应用程序看起来如下所示的Genymotion VD:

HelloLambda应用程序

您可以在LogCat窗口中观察到带有简单lambda表达式的代码片段正常工作

来源:在Android开发工具中使用Java 8 Lambda表达式

添加以下内容修复了我的问题(Android studio 2.3.2):

构建。gradle(项目)

buildscript {
repositories {
    ...
    jcenter()
}
dependencies {
    ...
    classpath 'me.tatarka:gradle-retrolambda:3.4.0' // DEPENDENCY
    ...
   }
}

构建。gradle(模块:app)

apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda' //PLUGIN

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    } // SET JAVA VERSION
    ...
}