Можно ли использовать Java 8 для разработки под Android?
При поиске в Интернете неясно, поддерживается ли Java 8 для разработки под Android или нет.
Прежде чем я загружу / настрою Java 8, может ли кто-нибудь указать мне на какую-либо "официальную" документацию, в которой говорится, поддерживается Java 8 для разработки под Android или нет.
Переведено автоматически
Ответ 1
ОБНОВЛЕНИЕ 2017/11/04 - Android Studio 3.0 теперь имеет встроенную поддержку Java 8. gradle-retrolambda
теперь она больше не нужна. Посмотреть https://developer.android.com/studio/write/java8-support.html
Приведенная выше ссылка также содержит инструкции по миграции, если вы используете gradle-retrolambda
. Оригинальный ответ ниже:
Android не поддерживает Java 8. Он поддерживает только до Java 7 (если у вас есть kitkat) и по-прежнему не имеет invokedynamic, только новый синтаксический сахар.
Если вы хотите использовать лямбды, одну из основных функций Java 8 в Android, вы можете использовать gradle-retrolamba. Это зависимость сборки gradle, которая интегрирует retrolambda, инструмент, который преобразует байт-код Java 8 обратно в Java 6/7. В принципе, если вы настроите компилятор в Android Studio на компиляцию байт-кода Java 8, тем самым разрешив лямбды, он преобразует его обратно в байт-код Java 6/7, который затем, в свою очередь, преобразуется в байт-код dalvik. Это хак на случай, если вы хотите опробовать некоторые функции JDK 8 в Android вместо официальной поддержки.
Ответ 2
Android поддерживает все функции языка Java 7 и подмножество функций языка Java 8, которые зависят от версии платформы.
Чтобы проверить, какие функции Java 8 поддерживаются
Используйте функции языка Java 8
Мы решили добавить поддержку функций языка Java 8 непосредственно в текущий набор инструментов javac и dx и отказаться от набора инструментов Jack. В этом новом направлении существующие инструменты и плагины, зависящие от формата файла класса Java, должны продолжать работать. В дальнейшем возможности языка Java 8 будут изначально поддерживаться системой сборки Android. Мы планируем запустить это как часть Android Studio в ближайшие недели, и мы хотели как можно раньше поделиться с вами этим решением.
Будущее поддержки языковых функций Java 8 на Android
Для старых разработчиков, предпочитающих Eclipse, Google прекращает поддержку Eclipse Android Developer tools
если вы установили Java 8 JDK, то попробуйте, если возникнут какие-либо проблемы, попробуйте установить компилятор как 1.6 в Eclipse из меню window → Настройки → Java → Компилятор. Java 7 тоже будет работать:
Java 7 or higher is required if you are targeting Android 5.0 and
higher.
install multiple JDK and try.
Ответ 3
You can indeed use gradle-retrolamba
gradle build dependency to use Java 8 for Android Development.
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.
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.
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:
http://code.google.com/p/android/issues/detail?id=72591
Steps in this guide will be given for a Windows 8.1 64-bit development 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:
bin
folder to your %PATH%
variableJAVA_HOME
with the value of the path of JDK 8 home folderJAVA8_HOME
again with the value of the path of JDK 8 home folderJAVA7_HOME
with the value of the path of JDK 7 home folderjava -version
command and verify that Java 8 is up and runningjavac -version
command in the same window and verify that JDK 8 Java compiler is also up and runningNow, ADT-22.6.2 must be downloaded from the following link:
http://dl.google.com/android/adt/22.6.2/adt-bundle-windows-x86_64-20140321.zip
D:\adt
ANDROID_HOME
with the value of the path of your ADT installation folder, e.g. D:\adt\sdk
Android SDK Platform Tools
and Android SDK Tools
folders, e.g. D:\adt\sdk\tools
and D:\adt\sdk\platform-tools
, to your %PATH%
variableD:\adt\eclipse
D:\adt\workspace
Android SDK Manager
button which is located on the toolbarAndroid SDK Build tools Rev. 19.1
and Android Support Library
only. Un-select everything else and install these two packages.If everything goes well, ADT will be up and running.
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 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
Below is a screenshot of an Android 4.3 based CyanogenMod virtual device,
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:
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:
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.
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:
File -> New -> Other -> Android -> Android Application Project
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:
Project -> Build Automatically
menu optionProperties -> Builders
and un-select all default builders provided by ADTNew
button in the same window and select Program
and click OK
Main
Tab of the new Builder Configuration
Refresh
Tab of the new Builder Configuration
Environment
Tab of the new Builder Configuration
Build Options
Tab of the new Builder Configuration
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.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.New Builders of the HelloLambda
Project
Export
Android -> Generate Gradle Build Files
and click Next
Finish
gradlew
and gradlew.bat
. Also delete gradle
folderProject -> Clean
menu option. Fill in the form that shows up as follows:Clean Project
Window
OK
and wait till the cleaning process completessetContentView
function in your MainActivity
class:build.gradle
file till the sourceCompatibility
section as follows:Properties -> Java Compiler
option and set all compliance levels to Java 8. This will make Eclipse recognize new Java 8 constructs like lambda expressions.No
in the notification windowBuild project
. Eclipse will start building the project.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
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.
Run Configuration
for your Android target platform by right-clicking on the project and then selecting Run As -> Run Configurations
. For instance, this demo application looks like shown below on the Genymotion VD:You may observe in the LogCat
window that the code snippet with a simple lambda expression works properly
Source: Using Java 8 Lambda Expressions in Android Developer Tools
Ответ 4
Follow this link for new updates. Use Java 8 language features
Old Answer
As of Android N preview release Android support limited features of Java 8 see Java 8 Language Features
To start using these features, you need to download and set up Android
Studio 2.1 and the Android N Preview SDK, which includes the
required Jack toolchain 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.
Supported Java 8 Language Features and APIs
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:
Default and static interface methods
Lambda expressions (also available on API level 23 and lower)
Method References (also available on API level 23 and lower)
There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features
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.
Update 2
Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features (without the Jack compiler).