是否可以将 Java 8 用于 Android 开发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23318109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use Java 8 for Android development?
提问by nPn
Searching the web, it is not clear if Java 8 is supported for Android development or not.
网上搜了一下,不清楚Android开发是否支持Java 8。
Before I download/setup Java 8, can some one point me at any "official" documentation that says Java 8 is or is not supported for Android development.
在我下载/安装 Java 8 之前,有人可以指出我在任何“官方”文档中说 Java 8 支持或不支持 Android 开发。
采纳答案by Eng. Samer T
java 8
爪哇 8
Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version.
Android 支持所有 Java 7 语言功能和 Java 8 语言功能的一个子集,这些功能因平台版本而异。
To check which features of java 8 are supported
检查支持 Java 8 的哪些功能
We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Hyman toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you.
我们决定将 Java 8 语言特性的支持直接添加到当前的 javac 和 dx 工具集中,并弃用 Hyman 工具链。有了这个新方向,依赖于 Java 类文件格式的现有工具和插件应该继续工作。展望未来,Android 构建系统将原生支持 Java 8 语言功能。我们的目标是在未来几周内将其作为 Android Studio 的一部分发布,我们希望尽早与您分享这一决定。
Future of Java 8 Language Feature Support on Android
Eclipse Users:
Eclipse 用户:
For old developers who prefer Eclipse, google stops support Eclipse Android Developer tools
对于喜欢 Eclipse 的老开发者,google 停止支持 Eclipse Android 开发者工具
if you installed Java 8 JDK, then give it a try, if any problems appears try to set the compiler as 1.6 in Eclipse from window menu → Preferences→ Java→ Compiler. Java 7 will works too:
如果您安装了 Java 8 JDK,请尝试一下,如果出现任何问题,请尝试从窗口菜单 → Preferences→ Java→ Compiler在 Eclipse 中将编译器设置为 1.6 。Java 7 也可以工作:
Java 7 or higher is required if you are targeting Android 5.0 and higher.
如果您的目标是 Android 5.0 及更高版本,则需要 Java 7 或更高版本。
install multiple JDK and try.
安装多个JDK并尝试。
回答by ekcr1
UPDATE 2017/11/04 - Android Studio 3.0 now has native support for Java 8.gradle-retrolambda
is now no longer needed. See https://developer.android.com/studio/write/java8-support.html
更新 2017/11/04 - Android Studio 3.0 现在原生支持 Java 8。gradle-retrolambda
现在不再需要。见https://developer.android.com/studio/write/java8-support.html
The above link also includes migration instructions if you are using gradle-retrolambda
. Original answer below:
如果您使用的是gradle-retrolambda
. 原答案如下:
Android does not support Java 8. It only supports up to Java 7 (if you have kitkat) and still it doesn't have invokedynamic, only the new syntax sugar.
Android 不支持 Java 8。它最多只支持 Java 7(如果你有 kitkat)而且它仍然没有调用动态,只有新的语法糖。
If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba. It's a gradle build dependency that integrates retrolambda, a tool that converts Java 8 bytecode back to Java 6/7. Basically, if you set the compiler in Android Studio to compile Java 8 bytecode, thus allowing lambdas, it'll convert it back to Java 6/7 bytecode which then in turn gets converted to dalvik bytecode. It's a hack for if you want to try out some JDK 8 features in Android in lieu of official support.
如果您想使用 lambdas(Android 中 Java 8 的主要特性之一),您可以使用gradle-retrolamba。它是一个集成了retrolambda 的gradle 构建依赖项,retrolambda 是一种将Java 8 字节码转换回Java 6/7 的工具。基本上,如果您在 Android Studio 中将编译器设置为编译 Java 8 字节码,从而允许使用 lambda,它会将其转换回 Java 6/7 字节码,然后再将其转换为 dalvik 字节码。如果您想在 Android 中尝试一些 JDK 8 功能来代替官方支持,这是一个技巧。
回答by chaqke
Android uses a Java that branches off of Java 6.
Android 使用从 Java 6 分支出来的 Java。
As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).
从 Android SDK 版本 19 开始,您可以通过执行此操作来使用 Java 7 功能。不完全支持 Java 8(还)。
回答by Sufiyan Ghori
You can indeed use gradle-retrolamba
gradle build dependency to use Java 8 for Android Development.
您确实可以使用gradle-retrolamba
gradle 构建依赖项来使用 Java 8 进行 Android 开发。
Below is the complete guide that I have recently followed to run lambda expressions for Android development. The original source of this guide is mentioned at the end.
下面是我最近为 Android 开发运行 lambda 表达式所遵循的完整指南。本指南的原始来源在最后提到。
In this guide, a method for bringing some Java 8features 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/orfHymanal/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.
在本指南中,将演示将一些Java 8功能引入 Android 开发工具的方法,特别是针对 Eclipse IDE. 但是,本指南中将描述的步骤也可能适用于 Google 的新开发环境 Android Studio。它基于 JetBrains 流行的 IntelliJ Idea IDE 的社区版,并且最近在 2014 年 7 月上旬由 Google 升级到了“测试版”,比编写本指南稍早一些。Eclipse 仍将是主要的开发环境,至少在一段时间内,考虑到大多数 Android 项目都是使用 Eclipse 开发的,将 lambda 表达式等新的 Java 8 特性引入 ADT 的方法似乎对开发人员非常有用。
Android 开发基于名为 Apache Harmony 项目的自定义 Java 实现,该实现于 2011 年终止。Android 开发中最常用的 Java 语法是 Java 6 (v1.6),Java 7 (v1.7) 也部分支持KitKat 版(Android 4.4.+)。因此,如果不对开发工具进行一些调整,则无法在 Android 应用程序开发中直接使用 Java 8 功能(如 lambda 表达式)。幸运的是,这些构造基本上是一些“语法糖”增强功能,它们为开发人员提供了诸如“匿名类”之类的缺点,并且可以将它们转换为 Java 6 或 Java 7 类。
最近将 Java 8 源代码翻译成较低 Java 版本的一种方法称为RetroLambda。该库使开发人员可以在 Java 7 或更低版本上使用 lambda 表达式运行 Java 8 代码。不幸的是,RetroLambda 目前不支持 lambda 表达式以外的 Java 8 功能,但 lambda 表达式的概念是 Java 8 平台上最大的飞跃,无论如何它是 Android 开发人员的一个很好的工具。
关于这个库的详细信息可以在它的 GitHub 页面上找到:
https://github.com/orfHymanal/retrolambda#getting-started
此外,另一个开发人员为 RetroLambda 创建的 Gradle 插件允许在 Java 或 Android 项目中实现基于 Gradle 的构建。但是,开发者只提到了将此插件集成到Android Studio环境中。详细信息可以在其 GitHub 页面上找到:
https://github.com/evant/gradle-retrolambda
在基于 Eclipse 的开发环境中使用这些基础设施无法直接实现,但它是可行的,并将在本指南中进行演示。
Preparation
准备
This guide assumes that the reader has a basic understanding of Android Development and it is based on ADT version 22.6.2 because recent ADT version 23.0.2 seems to have problems like layout folder creation. Details about this issue can be found under the following link:
本指南假设读者对 Android 开发有基本的了解,它基于 ADT 版本 22.6.2,因为最近的 ADT 版本 23.0.2 似乎存在布局文件夹创建等问题。可以在以下链接中找到有关此问题的详细信息:
http://code.google.com/p/android/issues/detail?id=72591
http://code.google.com/p/android/issues/detail?id=72591
Steps in this guide will be given for a Windows 8.1, 64-bitdevelopment machine but they can easily be adapted to other platforms. The new build system Gradle
will be used for build/clean processes and its installation procedure will also be provided. Also, both JDK 8
and JDK 7
must coexist on the development machine. Steps given below must be followed to install them:
本指南中的步骤将针对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
- 转至 JDK 8 早期访问预览页面http://jdk8.java.net
- 下载 JDK 8u20 并安装。JRE 8 安装不是必须的,可以跳过
- 转至 JDK 7 最新稳定版页面http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
- 下载 JDK 7u65 并安装。再次不需要安装 JRE 7,可以跳过
- 将 JDK 8 主文件夹和 JDK 8
bin
文件夹添加到您的%PATH%
变量中 JAVA_HOME
使用 JDK 8 主文件夹路径的值创建一个新的环境变量JAVA8_HOME
使用JDK 8主文件夹路径的值再次创建一个新的环境变量JAVA7_HOME
使用 JDK 7 主文件夹路径的值创建一个新的环境变量- 打开终端窗口并运行
java -version
命令并验证 Java 8 是否已启动并正在运行 javac -version
在同一窗口中运行命令并验证 JDK 8 Java 编译器是否也已启动并正在运行
Now, ADT-22.6.2 must be downloaded from the following link:
现在,必须从以下链接下载 ADT-22.6.2:
http://dl.google.com/android/adt/22.6.2/adt-bundle-windows-x86_64-20140321.zip
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
Andoid SDK Platform Tools
andAndoid SDK Tools
folders, e.g.D:\adt\sdk\tools
andD:\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
andAndroid Support Library
only. Un-select everything else and install these two packages.
- 下载 ADT 并将其内容解压缩到一个文件夹中,例如
D:\adt
- 定义一个
ANDROID_HOME
使用 ADT 安装文件夹路径值调用的新环境变量,例如D:\adt\sdk
- 将您的
Andoid SDK Platform Tools
andAndoid SDK Tools
文件夹,例如D:\adt\sdk\tools
andD:\adt\sdk\platform-tools
,添加到您的%PATH%
变量中 - 如果愿意,可以创建 Eclipse IDE 的快捷方式。它位于您的 ADT 安装文件夹下,例如
D:\adt\eclipse
- 运行 Eclipse IDE 并创建一个工作区,例如
D:\adt\workspace
- 单击
Android SDK Manager
位于工具栏上的按钮 - 选择
Android SDK Build tools Rev. 19.1
且Android Support Library
仅。取消选择其他所有内容并安装这两个软件包。
If everything goes well, ADT will be up and running.
如果一切顺利,ADT 将启动并运行。
The installation of the following tools is also highly recommended:
还强烈建议安装以下工具:
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 throughHelp -> Install New Software
in Eclipse. Enter http://download.eclipse.org/eclipse/updates/4.3-P-builds/into theWork 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 withEclipse Marketplace Client
. Therefore, you will first need to installEclipse Marketplace Client
by means ofInstall New Software
tool in Eclipse. Enter http//:download.eclipse.org/mpc/kepler/ into theWork with
field and continue to install it. After installingEclipse Marketplace Client
, you may search forNodeclipse/Enide Gradle
in theEclipse 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 usingCyanogenMod
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:
Eclipse Kepler Java 8 支持:它使 Eclipse 能够识别新的 Java 8 语法扩展,并使您摆脱
red dots
Java 代码编辑器中的烦人。它可能是通过Help -> Install New Software
Eclipse安装的。在该字段中输入http://download.eclipse.org/eclipse/updates/4.3-P-builds/Work with
并继续安装它。Nodeclipse/Enide Gradle:主要用于高亮Groovy语言关键字。Groovy 用作 Gradle 构建脚本的 DSL。这个插件可以通过
Eclipse Marketplace
. 但是,ADT-22.6.2 中的 Eclipse 不附带Eclipse Marketplace Client
. 因此,您首先需要Eclipse Marketplace Client
通过Install New Software
Eclipse 中的工具进行安装。在Work with
字段中输入 http//:download.eclipse.org/mpc/kepler/并继续安装。安装完成后Eclipse Marketplace Client
,你可以搜索Nodeclipse/Enide Gradle
在Eclipse Marketplace Client
并安装它。Genymotion 虚拟设备:它是
Android Virtual Device
ADT 附带的默认设备的绝佳替代品。AVD 很烦人,而且总是无缘无故地崩溃。Genymotion 使您可以使用CyanogenMod
由Oracle VirtualBox执行的图像来准备 Android VD 。它的单用户许可证是免费的,可以从http://www.genymotion.com下载。只需要登录,它也可以集成到 Eclipse 中。详细信息可以在下面找到:
https://cloud.genymotion.com/page/doc/#collapse8
https://cloud.genymotion.com/page/doc/#collapse8
Below is a screenshot of an Android 4.3 based CyanogenMod virtual device,
下面是一个基于 Android 4.3 的 CyanogenMod 虚拟设备的屏幕截图,
It might be considered as a fully-fledge Android device running on a x86 or x64 based personal computer. In order to use Google services like Google PlayStore
on this virtual device, a gapps
image for the Android version that it uses must be flashed onto the device. A proper gapps
image for the device might be downloaded from CyanogenMod website:
它可以被视为在基于 x86 或 x64 的个人计算机上运行的成熟的 Android 设备。为了Google PlayStore
在此虚拟设备上使用 Google 服务,gapps
必须将其使用的 Android 版本的映像刷入设备。一个适当gapps
的设备图像可以从CyanogenMod的网站上下载:
http://wiki.cyanogenmod.org/w/Google_Apps
http://wiki.cyanogenmod.org/w/Google_Apps
Gradle installation is optional since it is also provided by Android SDK itself but its separate installation is highly recommended. Installation of it might be conducted by following these steps:
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.
转到 Gradle 网站:http: //www.gradle.org/
点击
Downloads
- 在
Previous Releases
选择版本 1.10 并下载 gradle-1.10-all.zip 或 gradle-1.10-bin.zip - 将其内容解压缩到一个文件夹中,例如
D:\adt\gradle
- 定义一个
GRADLE_HOME
使用 Gradle 安装文件夹路径值调用的新环境变量,例如D:\adt\gradle
- 将您的 Gradle 二进制文件文件夹,例如
D:\adt\gradle\bin
,添加到您的%PATH%
变量 - 打开一个终端窗口并运行
gradle -v
命令并验证它是否已启动并正在运行 如果您已成功完成这一点,则意味着您已准备好使用 Java 8 功能创建您的第一个 Android 应用程序。
Demo App
演示应用
A simple app will be created to demonstrate the usage of the tools which were described in the previous section. You may simply follow the steps given below to get an insight on using lambda expressions in Android Developer Tools:
将创建一个简单的应用程序来演示上一节中描述的工具的用法。你可以简单地按照下面给出的步骤来深入了解在 Android 开发者工具中使用 lambda 表达式:
- Run Eclipse IDE and create a new Android App by selecting
File -> New -> Other -> Android -> Android Application Project
- Fill in the form that comes up as shown below:
- 运行 Eclipse IDE 并通过选择创建一个新的 Android 应用程序
File -> New -> Other -> Android -> Android Application Project
- 填写出现的表格,如下所示:
- Simply click the
Next
button on the following forms and click theFinish
button on the last one. Wait till ADT finishes loading up the project - Right-click on the project and select
New -> Folder
and name itbuilders
- 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:
- 只需单击
Next
以下表格上的Finish
按钮,然后单击最后一个表格上的按钮。等待 ADT 完成加载项目 - 右键单击项目并选择
New -> Folder
并命名它builders
- 右键单击该
gen (Generated Java Files)
文件夹并将其删除。Gradle 很快就会为我们生成相同的文件,我们会将它们添加到s build path. The
默认 Ant 构建器创建的项目gen` 文件夹中,不再需要该文件夹下的工件 在
builders
文件夹下创建以下批处理文件:- gradle_build.cmd
- gradle_post_build.cmd
- gradle_clean.cmd
填写这些批处理文件如下:
gradle_build.cmd:
gradle_build.cmd:
gradle_post_build.cmd:
gradle_post_build.cmd:
gradle_clean.cmd:
gradle_clean.cmd:
- Un-select
Project -> Build Automatically
menu option - Right-click on the project and select
Properties -> Builders
and un-select all default builders provided by ADT - Click the
New
button in the same window and selectProgram
and clickOK
- New builder configuration window will appear. Fill in its tabs as follows:
- 取消选择
Project -> Build Automatically
菜单选项 - 右键单击项目并选择
Properties -> Builders
并取消选择 ADT 提供的所有默认构建器 - 单击
New
同一窗口中的按钮,然后选择Program
并单击OK
- 将出现新的构建器配置窗口。按如下方式填写其选项卡:
Main
Tab of the new Builder Configuration
Main
新的 Builder 配置选项卡
Refresh
Tab of the new Builder Configuration
Refresh
新的 Builder 配置选项卡
Environment
Tab of the new Builder Configuration
Environment
新的 Builder 配置选项卡
Build Options
Tab of the new Builder Configuration
Build Options
新的 Builder 配置选项卡
- Create the second builder called
Gradle_Post_Build
that usesgradle_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 thebin
folder. - Create the third builder called
Gradle_Cleaner
that usesgradle_clean.cmd
as its program. OnlyRun the builder
setting in the final tab must be set asDuring 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.
- 创建调用的第二个构建器
Gradle_Post_Build
,gradle_post_build.cmd
用作其程序。此构建器的所有其他设置必须与之前创建的构建器完全相同。该构建器将负责将构建过程创建的工件复制到bin
文件夹中。 - 创建调用的第三个构建器
Gradle_Cleaner
,gradle_clean.cmd
用作其程序。只有Run the builder
在最后一个选项卡中的设置必须设置为During a Clean
。此构建器的所有其他设置必须与第一个构建器完全相同。顾名思义,这个构建器将负责清理构建过程创建的工件。
New Builders of the HelloLambda
Project
HelloLambda
项目的新建设者
- Right-click on the project and select
Export
- Select
Android -> Generate Gradle Build Files
and clickNext
- Select the project in the next window and click
Finish
- Go to your project's root folder and delete the files
gradlew
andgradlew.bat
. Also deletegradle
folder - Switch back to Eclipse and select
Project -> Clean
menu option. Fill in the form that shows up as follows:
- 右键单击项目并选择
Export
- 选择
Android -> Generate Gradle Build Files
并点击Next
- 在下一个窗口中选择项目并单击
Finish
- 转到项目的根文件夹并删除文件
gradlew
和gradlew.bat
. 也删除gradle
文件夹 - 切换回 Eclipse 并选择
Project -> Clean
菜单选项。填写如下所示的表格:
Clean Project
Window
Clean Project
窗户
- Click
OK
and wait till the cleaning process completes - Add the Java code snippet given below right after the call to
setContentView
function in yourMainActivity
class:
- 单击
OK
并等待清洁过程完成 setContentView
在MainActivity
类中调用函数之后添加下面给出的 Java 代码片段:
- Change the beginning of the
build.gradle
file till thesourceCompatibility
section as follows:
- 将
build.gradle
文件的开头更改sourceCompatibility
为以下部分:
- Right-click on the project and select
Properties -> Java Compiler
option and set all compliance levels to Java 8. This will make Eclipse recognize new Java 8 constructs like lambda expressions. - Click
No
in the notification window - Right-click on the project and select
Build project
. Eclipse will start building the project.
- 右键单击该项目并选择
Properties -> Java Compiler
选项并将所有合规性级别设置为 Java 8。这将使 Eclipse 识别新的 Java 8 构造,如 lambda 表达式。 - 点击
No
通知窗口 - 右键单击项目并选择
Build project
。Eclipse 将开始构建项目。
Build Process
构建过程
Right-click on the project and go to
Properties -> Java Build Path
. Add the following folders to the build path (also shown in below image):build\source\buildConfig\debug
build\source\r\debug
右键单击该项目并转到
Properties -> Java Build Path
。将以下文件夹添加到构建路径(也如下图所示):build\source\buildConfig\debug
build\source\r\debug
Eclipse will now be able to recognize R.java
and buildConfig.java
files and it will not display any red dots
which denote errors related to the resource files of the project.
现在Eclipse将能够识别R.java
和buildConfig.java
文件,它不会显示任何red dots
有关该项目的资源文件时分别表示错误。
- Create a new
Run Configuration
for your Android target platform by right-clicking on the project and then selectingRun As -> Run Configurations
. For instance, this demo application looks like shown below on the Genymotion VD:
- 创建一个新的
Run Configuration
通过在项目上右击,然后选择您的Android目标平台Run As -> Run Configurations
。例如,这个演示应用程序在 Genymotion VD 上如下所示:
HelloLambda Application
HelloLambda 应用程序
You may observe in the LogCat
window that the code snippet with a simple lambda expression works properly
您可能会在LogCat
窗口中观察到带有简单 lambda 表达式的代码片段工作正常
Source: Using Java 8 Lambda Expressions in Android Developer Tools
回答by sivi
Yes, Android Supports Java 8 Now (24.1.17)
是的,Android 现在支持 Java 8 (24.1.17)
Now it is possible
现在有可能
But you will need to have your device rom run on java 1.8 and enable "HymanOptions" to run it. Hyman is the name for the new Android compiler that runs Java 8
但是您需要让您的设备 rom 在 java 1.8 上运行并启用“HymanOptions”才能运行它。Hyman 是运行 Java 8 的新 Android 编译器的名称
https://developer.android.com/guide/platform/j8-Hyman.html
https://developer.android.com/guide/platform/j8-Hyman.html
add these lines to build_gradle
将这些行添加到 build_gradle
android {
...
defaultConfig {
...
HymanOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Java 8 seem to be the running java engine of Android studio 2.0, But it still does not accept the syntax of java 8 after I checked, and you cannot chose a compiler from android studio now. However, you can use the scala plugin if you need functional programming mechanism in your android client.
Java 8好像是Android studio 2.0运行的java引擎,但是我查了一下还是不接受java 8的语法,现在也不能选择android studio的编译器了。但是,如果您的 android 客户端需要函数式编程机制,则可以使用 scala 插件。
回答by Vishal Raj
We Can Use Java 8 using:
我们可以使用 Java 8 使用:
In build.gradle (Project: myProject) add following
classpath 'me.tatarka:gradle-retrolambda:x.x.x' //x.x.x is recent version
In build.gradle (Module: myModule) add following
apply plugin: 'me.tatarka.retrolambda' compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
在 build.gradle (Project: myProject) 添加以下内容
classpath 'me.tatarka:gradle-retrolambda:x.x.x' //x.x.x is recent version
在 build.gradle (Module: myModule) 添加以下内容
apply plugin: 'me.tatarka.retrolambda' compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
回答by nPn
When I asked this question almost 2 years ago the answer really was “officially” no, but as pointed out by ekcr1's answer you can get one of the most highly anticipated features (lambdas) to work if you use retrolamba. At the time I was still using eclipse, as Android Studio was in “preview” mode, so I never did pursue this path.
大约 2 年前,当我问这个问题时,答案确实是“正式”否,但正如 ekcr1 的回答所指出的那样,如果您使用 retrolamba,您可以获得最受期待的功能 (lambdas) 之一。当时我还在用 eclipse,因为 Android Studio 处于“预览”模式,所以我从来没有走这条路。
Today, I think the “official” answer is still no, and while retrolamba still seems like a good way to go, there is another option for those willing to go down a somewhat “unofficial” route can take, namely Kotlin.
今天,我认为“官方”的答案仍然是否定的,虽然 retrolamba 似乎仍然是一个不错的选择,但对于那些愿意走“非官方”路线的人来说,还有另一种选择,即 Kotlin。
Today Kotlin reached 1.0.0. For those not familiar with Kotlin, more info can be found at their website found here:
今天 Kotlin 达到了 1.0.0。对于那些不熟悉 Kotlin 的人,可以在他们的网站上找到更多信息:
or watch this utube video of a talk given by Jake Wharton
或观看 Jake Wharton 演讲的 utube 视频
回答by Jay
Android OFFICIALLY supports Java 8 as of Android N.
从 Android N 开始,Android 正式支持 Java 8。
Feature announcements are here, the Java 8 language announcement is:
功能公告在这里,Java 8 语言公告是:
Improved Java 8 language support- We're excited to bring Java 8 language features to Android. With Android's Hyman 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 Hyman, we're looking forward to tracking the Java language more closely while maintaining backward compatibility.
改进的 Java 8 语言支持- 我们很高兴将 Java 8 语言功能引入 Android。借助 Android 的 Hyman 编译器,您现在可以在 Gingerbread 等 Android 版本上使用许多流行的 Java 8 语言功能,包括 lambdas 等。新功能有助于减少样板代码。例如,在提供事件侦听器时,lambda 可以替换匿名内部类。一些 Java 8 语言特性——比如默认和静态方法、流和函数式接口——现在也可以在 N 和更高版本上使用。对于 Hyman,我们期待在保持向后兼容性的同时更密切地跟踪 Java 语言。
回答by Jay
Follow this link for new updates. Use Java 8 language features
按照此链接获取新更新。使用 Java 8 语言特性
Old Answer
旧答案
As of Android N previewrelease Android support limitedfeatures of Java 8see Java 8 Language Features
从Android N 预览版开始,Android 支持Java 8 的有限功能,请参阅Java 8 语言功能
To start using these features, you need to download and set up Android Studio 2.1and the Android N Preview SDK, which includes the required Hymantoolchain and updated Android Plugin for Gradle. If you haven't yet installed the Android N Preview SDK, see Set Up to Develop for Android N.
要开始使用这些功能,您需要下载并设置Android Studio 2.1和 Android N Preview SDK,其中包括所需的Hyman工具链和更新的 Android Plugin for Gradle。如果您尚未安装 Android N Preview SDK,请参阅设置以针对 Android N 进行开发。
Supported Java 8 Language Features and APIs
支持的 Java 8 语言功能和 API
Android does not currently support all Java 8 language features. However, the following features are now available when developing apps targeting the Android N Preview:
Android 目前不支持所有 Java 8 语言功能。但是,在开发面向 Android N 预览版的应用程序时,现在可以使用以下功能:
Default and static interface methods
Lambda expressions(also available on API level 23 and lower)
Lambda 表达式(也可用于 API 级别 23 及更低级别)
Method References(also available on API level 23 and lower)
方法参考(也可用于 API 级别 23 及更低级别)
There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features
Android 支持一些额外的 Java 8 功能,您可以从Java 8 语言功能中查看完整的详细信息
Update
更新
Note: The Android N bases its implementation of lambda expressions on anonymous classes. This approach allows them to be backwards compatible and executable on earlier versions of Android. To test lambda expressions on earlier versions, remember to go to your build.gradle file, and set compileSdkVersion and targetSdkVersion to 23 or lower.
注意:Android N 基于匿名类实现 lambda 表达式。这种方法允许它们向后兼容并且可以在早期版本的 Android 上执行。要在早期版本上测试 lambda 表达式,请记住转到您的 build.gradle 文件,并将 compileSdkVersion 和 targetSdkVersion 设置为 23 或更低。
Update 2
更新 2
Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features(without the Hyman compiler).
现在 Android studio 3.0 稳定版支持Java 8 库和 Java 8 语言特性(没有 Hyman 编译器)。
回答by Dhaval Jivani
Native Java 8 arrives on android! Finally!
原生 Java 8 登陆安卓!最后!
remove the Retrolambda plugin and retrolambda block from each module's build.gradle file:
To disable Hyman and switch to the default toolchain, simply remove the HymanOptions block from your module's build.gradle file
从每个模块的 build.gradle 文件中删除 Retrolambda 插件和 retrolambda 块:
要禁用 Hyman 并切换到默认工具链,只需从模块的 build.gradle 文件中删除 HymanOptions 块
To start using supported Java 8 language features, update the Android plugin to 3.0.0 (or higher)
要开始使用受支持的 Java 8 语言功能,请将 Android 插件更新到 3.0.0(或更高版本)
Starting with Android Studio 3.0 , Java 8 language features are now natively supported by android:
从 Android Studio 3.0 开始,Android 原生支持 Java 8 语言功能:
- Lambda expressions
- Method references
- Type annotations (currently type annotation information is not available at runtime but only on compile time);
- Repeating annotations
- Default and static interface methods (on API level 24 or higher, no instant run support tho);
- Lambda 表达式
- 方法参考
- 类型注释(目前类型注释信息在运行时不可用,只能在编译时可用);
- 重复注释
- 默认和静态接口方法(在 API 级别 24 或更高级别上,不支持即时运行);
Also from min API level 24 the following Java 8 API are available:
同样从最低 API 级别 24 开始,以下 Java 8 API 可用:
- java.util.stream
- java.util.function
- java.lang.FunctionalInterface
- java.lang.annotation.Repeatable
- java.lang.reflect.AnnotatedElement.getAnnotationsByType(Class)
- java.lang.reflect.Method.isDefault()
- java.util.stream
- java.util.function
- java.lang.FunctionalInterface
- java.lang.annotation.Repeatable
- java.lang.reflect.AnnotatedElement.getAnnotationsByType(Class)
- java.lang.reflect.Method.isDefault()
Add these lines to your application module's build.gradle to inform the project of the language level:
将这些行添加到您的应用程序模块的 build.gradle 以通知项目语言级别:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Disable Support for Java 8 Language Features by adding the following to your gradle.propertiesfile:
通过将以下内容添加到gradle.properties文件来禁用对 Java 8 语言功能的支持:
android.enableDesugar=false
You're done! You can now use native java8!
你完成了!您现在可以使用本机 java8!