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

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


当前回答

我想我应该发布一个更新的答案给那些寻找一些更当前的东西的人。

目前Android和Android Studio支持Java 8特性的一个子集。根据他们网站上的Android文档,谷歌说:

Support for Java 8 language features requires a new compiler called Jack. Jack is supported only on Android Studio 2.1 and higher. So if you want to use Java 8 language features, you need to use Android Studio 2.1 to build your app. If you already have Android Studio installed, make sure you update to the latest version by clicking Help > Check for Update (on Mac, Android Studio > Check for Updates). If you don't already have the IDE installed on your workstation, download Android Studio here. Supported Java 8 Language Features and APIs Android does not support all Java 8 language features. However, the following features are available when developing apps targeting Android 7.0 (API level 24): Default and static interface methods Lambda expressions (also available on API level 23 and lower) Repeatable annotations Method References (also available on API level 23 and lower) Type Annotations (also available on API level 23 and lower)

此外,以下Java 8语言api也可用:

Reflection and language-related APIs: java.lang.FunctionalInterface java.lang.annotation.Repeatable java.lang.reflect.Method.isDefault() and Reflection APIs associated with repeatable annotations, such as AnnotatedElement.getAnnotationsByType(Class) Utility APIs: java.util.function java.util.stream In order to use the new Java 8 language features, you need to also use the Jack toolchain. This new Android toolchain compiles Java language sources into Android-readable DEX bytecode, has its own .jack library format, and provides most toolchain features as part of a single tool: repackaging, shrinking, obfuscation and multidex. Here is a comparison of the two toolchains used to build Android DEX files: Legacy javac toolchain: javac (.java → .class) → dx (.class → .dex) New Jack toolchain: Jack (.java → .jack → .dex)

其他回答

我在3年前问过这个问题,很明显,这些年来答案已经发生了变化。正如上面许多人已经回答过的那样,就在不久前,答案变成了“是的”。我从来没有更新过被接受的答案,因为它是当时的正确答案。(我不确定堆栈溢出策略是什么)

我只是想给那些还在搜索这个话题的人补充一个答案。截至2017年5月17日,谷歌还宣布Kotlin也是Android开发的官方语言。

我还没有找到官方的新闻稿,但我确实看了一些谷歌的I/O视频。这里是Kotlin团队关于公告的一篇博客文章的链接。

Android在Android N正式支持Java 8。

特性公告如下,Java 8语言公告如下:

Improved Java 8 language support - We’re excited to bring Java 8 language features to Android. With Android's Jack compiler, you can now use many popular Java 8 language features, including lambdas and more, on Android versions as far back as Gingerbread. The new features help reduce boilerplate code. For example, lambdas can replace anonymous inner classes when providing event listeners. Some Java 8 language features --like default and static methods, streams, and functional interfaces -- are also now available on N and above. With Jack, we’re looking forward to tracking the Java language more closely while maintaining backward compatibility.

你确实可以使用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表达式

原生Java 8登陆android!终于!

从每个模块中删除Retrolambda插件和Retrolambda块 构建。gradle文件: 要禁用Jack并切换到默认工具链,只需删除 模块构建中的jackOptions块。gradle文件

要开始使用受支持的Java 8语言特性,请将Android插件更新到3.0.0(或更高版本)

从Android Studio 3.0开始,Java 8语言功能现在原生支持Android:

Lambda表达式 方法引用 类型注释(目前类型注释信息在运行时不可用,只在编译时可用); 重复注释 默认和静态接口方法(API级别24或更高,不支持即时运行);

另外,从最低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 ()

将这些行添加到应用程序模块的构建中。Gradle告知项目的语言级别:

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

通过在gradle中添加以下内容禁用对Java 8语言特性的支持。属性文件:

android.enableDesugar=false

你已经完成了!您现在可以使用本机java8!

在2019年最新的Android Studio 3.4+上,上述所有解决方案似乎都不起作用。

我想出了一个完美的和最新的解决方案,将您的Android项目迁移或升级到Java 8。

解决方案: 点击文件->项目结构->模块->属性选项卡。 将源兼容性和目标兼容性更改为1.8 (Java 8)