Java 8 collection.stream() API in android [duplicate] - java
Searching the web, it is not clear if Java 8 is supported for Android development or not.
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.
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
The above link also includes migration instructions if you are using gradle-retrolambda. Original answer below:
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.
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.
java 8
Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version.
To check which features of java 8 are supported
Use Java 8 language features
We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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.
Future of Java 8 Language Feature Support on Android
Eclipse Users:
For old developers who prefer Eclipse, google stops support Eclipse Android Developer tools
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 7 or higher is required if you are targeting Android 5.0 and
higher.
install multiple JDK and try.
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.
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:
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:
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
Now, 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
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.
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.
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:
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:
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:
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 select Program and click OK
New builder configuration window will appear. Fill in its tabs as follows:
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
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.
New Builders of the HelloLambda Project
Right-click on the project and select Export
Select Android -> Generate Gradle Build Files and click Next
Select the project in the next window and click Finish
Go to your project's root folder and delete the files gradlew and gradlew.bat. Also delete gradle folder
Switch back to Eclipse and select Project -> Clean menu option. Fill in the form that shows up as follows:
Clean Project Window
Click OK and wait till the cleaning process completes
Add the Java code snippet given below right after the call to setContentView function in your MainActivity class:
Change the beginning of the build.gradle file till the sourceCompatibility section as follows:
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.
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.
Create a new 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:
HelloLambda Application
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
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)
Repeatable annotations
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).
Yes, Android Supports Java 8 Now (24.1.17)
Now it is possible
But you will need to have your device rom run on java 1.8 and enable "jackOptions" to run it.
Jack is the name for the new Android compiler that runs Java 8
https://developer.android.com/guide/platform/j8-jack.html
add these lines to build_gradle
android {
...
defaultConfig {
...
jackOptions {
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.
Android uses a Java that branches off of Java 6.
As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).
Native Java 8 arrives on android! Finally!
remove the Retrolambda plugin and retrolambda block from each module's
build.gradle file:
To disable Jack and switch to the default toolchain, simply remove the
jackOptions block from your module’s build.gradle file
To start using supported Java 8 language features, update the Android plugin to 3.0.0 (or higher)
Starting with Android Studio 3.0 , Java 8 language features are now natively supported by android:
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);
Also from min API level 24 the following Java 8 API are available:
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:
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.properties file:
android.enableDesugar=false
You’re done! You can now use native java8!
Android OFFICIALLY supports Java 8 as of Android N.
Feature announcements are here, the Java 8 language announcement is:
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.
We Can Use Java 8 using:
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
}
UPDATE 2020/01/17
Android Studio 4.0 includes support for using a number of Java 8 language APIs, by using technique called desugaring, without requiring a minimum API level for your app:
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'
}
ORIGINAL POST FROM 2017
Android Studio 3.0 started to provide built-in support for some of Java 8 language features, which are:
Lambda expressions
Method references
Type Annotations (information is available at compile time, but not at runtime)
Repeating annotations
Default and static interface methods
Also starting from API level 24 the following Java 8 API are available:
java.util.stream
java.util.function
java.lang.FunctionalInterface
java.lang.annotation.Repeatable
java.lang.reflect.AnnotatedElement.getAnnotationsByType(Class)
java.lang.reflect.Method.isDefault()
Besides that, the try-with-resources support was extended to all Android API levels.
More Java 8 features are promised to be added in the future.
To start using supported Java 8 language features, update the Android
plugin to 3.0.0-alpha1 (or higher) and add the following to your
module’s build.gradle file:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
For more details visit:
https://developer.android.com/studio/write/java8-support.html
Easy way
You can enable java 1.8 support for android project.
Open Project Structure
Either by pressing Ctrl + Shift + Alt + S
Or File > Project Structure
Update the Source Compatibility and Target Compatibility to 1.8 in the Project Structure dialog as shown (click File > Project Structure).
Or you can use gradle
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Sync project. And that's it!
Note: Java 1.8 support can be enabled for Android Studio 3.0.0 or higher. See Documentation for further reading.
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.
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.
Today Kotlin reached 1.0.0. For those not familiar with Kotlin, more info can be found at their website found here:
https://kotlinlang.org
or watch this utube video of a talk given by Jake Wharton
https://www.youtube.com/watch?v=A2LukgT2mKc
Latest news:
Google announce that with Android N and Android Studio 2.1+, platform will support Java 8. Also stable version of studio 2.1 was released.
At last we can use lambda expressions. No more list filter in for loop. Horeeey.
Add this config build.gradle and sync gradle:
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
// or
//sourceCompatibility 1.8
//targetCompatibility 1.8
}
}
Google just announced that Java 8 will be natively support by Android and that the Jack toolchain will deprecate:
We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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.
More Info here:
https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html
Yes. We will use Java 8 soon!
We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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.
https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html
addd this line into module lvl build gradel
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
UPDATE 2019/10/28
Android Studio 4.0 solves this issue.
The D8 compiler patches a backport of the Java 8 native APIs into your APK at compile time and your app will use that code, instead of the native APIs, at runtime. The process is called desugaring.
I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer.
Android Studio 2.1:
The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post:
... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8.
...
To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File→ New→ Project] generates the correct configurations for projects targeting the N.
Prior to Android Studio 2.1:
Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas.
This answer gives more detail on Android Studio's compatibility; it states:
If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba
If you want to know more about using gradle-retrolambda, this answer gives a lot of detail on doing that.
I figured I would post an updated answer for those looking at for something a little more current.
Currently Android and Android Studio are supporting a subset of Java 8 features. According to the Android documentation located on their website, Google says:
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)
Additionally, the following Java 8 language APIs are also available:
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)
I asked this question over 3 years ago and obviously the answers have changed over the years. As many above have already answered, as of sometime back, the answer became Yes. I have never updated the accepted answer because it was the correct answer at the time. (I am not sure what the Stack Overflow policy is on that)
I just wanted to add another answer for those who still search for this topic. As of 5/17/2017 Google also announced that Kotlin is also an official language for Android development.
I have not found an official press release, but I did watch some of the Google I/O videos where it was announced. Here is a link to a blog post by the Kotlin team on the announcement.
Adding the following fixed the problem for me (Android studio 2.3.2):
build.gradle (Project)
buildscript {
repositories {
...
jcenter()
}
dependencies {
...
classpath 'me.tatarka:gradle-retrolambda:3.4.0' // DEPENDENCY
...
}
}
build.gradle (Module: 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
...
}
A subset of Java 8 is supported now on Android Studio. Just make the Source and Target Compatibility adjustments from the window below:
File --> Project Structure
More information is given in the below link.
https://developer.android.com/studio/write/java8-support.html
Easiest way to add Java 8 support
compileOptions {
targetCompatibility = '1.8'
sourceCompatibility = '1.8'
}
Just add it in your build.gradle file.
Android Gradle plugin 3.0.0 and later support all Java 7 language features and a subset of Java 8 language features that vary by platform version. When building your app using Android Gradle plugin 4.0.0 and higher, you can use a number of Java 8 language APIs without requiring a minimum API level for your app.
This page describes the Java 8 language features you can use, how to properly configure your project to use them, and any known issues you may encounter.
For this article will help you. I'll put the link here below down
https://developer.android.com/studio/write/java8-support
All the above solutions doesn't seem to work in 2019 with the latest Android Studio 3.4+.
I figured out a perfect and up to date solution to migrate or upgrade your Android Project to Java 8.
Solution:
Click on File -> Project Structure -> Modules -> Properties tab.
Change the Source Compatibility and Target Compatibility to 1.8 (Java 8)
Yes, you can use Java 8 Language features in Android Studio but the version must be 3.0 or higher. Read this article for how to use java 8 features in the android studio.
https://bijay-budhathoki.blogspot.com/2020/01/use-java-8-language-features-in-android-studio.html
EASY TO REMEMBER ANSWER
In android studio click on project structure icon then go inside Modules/app then change Source Compatibility and Target Compatibility to 1.8 and press Ok.
Related
How to add Java 9 to Android Studio?
I am using Robolectric library and the latest version of it v4.3.1 requires Java 9 to run. I am trying to point JRE on edit configurations but I am not finding Java 9 in the drop-down, even though I have already installed it. Please check Java 9 installed.
The only workaround to run Robolectric test in the Android Studio is to change JRE for the test task. Select IDE menu Run -> Edit Configuration and then change the option from the picture to the location of JDK9:
Tests can run on prior versions as a temporary workaround You will not be able to run Robolectric against SDK 29 for now (27 April 2020), but this will likely be updated in the future. Currently, as all of the answers before me pointed out, there is no support of Java 9 or later in Android Studio. But if you are here to make your Robolectic tests run you could simply avoid SDK 29 by setting the Robolectric #Config annotation for your class. Robolectric will simply run your tests against all of the supported SDK versions of your app except 29. Implement Set the maxSdk and minSdk versions to run on. This can be based on the app's min and max SDK versions, or set to one version like below in order to make tests faster. import androidx.test.ext.junit.runners.AndroidJUnit4 import org.robolectric.annotation.Config import org.junit.runner.RunWith import android.os.Build #RunWith(AndroidJUnit4::class) #Config(maxSdk = Build.VERSION_CODES.P, minSdk = Build.VERSION_CODES.P) // Value of Build.VERSION_CODES.P is 28 class TestClass { ... } Of course it is just another "ugly" patch, but it will get you going until you'll be able to run tests against all of the desired SDKs, or at least SDK 29 and all below.
So far Android doesn't support Java 9. As per documentation, Android supports all Java 7 features and a part of Java 8 features. When developing apps for Android, using Java 8 language features is optional. You can keep your project's source and target compatibility values set to Java 7, but you still need to compile using JDK 8.
I don't guarantee that it will work but you can set JDK to any version from the project Structure Option File>Project Structure>SDK Location>'change JDK location here' sorry but it's not working either i have tried to select JDK9 but i got a prompt like this
You can't use Java 9, Android only supports till Java 8. You should use the JDK version that comes with Android Studio, no need for side alone JDK. The current JDK version is based on OpenJDK 8.
In Android Studio, under "Build, Execution, Deployment => Gradle => Gradle JDK", you can choose the JDK version. In newer versions of Android Studio like Artic Fox, it comes with JDK11.
Old Android devices will be supported if I use Java 8? [duplicate]
Searching the web, it is not clear if Java 8 is supported for Android development or not. 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.
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 The above link also includes migration instructions if you are using gradle-retrolambda. Original answer below: 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. 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.
java 8 Android supports all Java 7 language features and a subset of Java 8 language features that vary by platform version. To check which features of java 8 are supported Use Java 8 language features We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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. Future of Java 8 Language Feature Support on Android Eclipse Users: For old developers who prefer Eclipse, google stops support Eclipse Android Developer tools 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 7 or higher is required if you are targeting Android 5.0 and higher. install multiple JDK and try.
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. 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: 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: 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 Now, 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 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. 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. 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: 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: 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: 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 select Program and click OK New builder configuration window will appear. Fill in its tabs as follows: 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 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. New Builders of the HelloLambda Project Right-click on the project and select Export Select Android -> Generate Gradle Build Files and click Next Select the project in the next window and click Finish Go to your project's root folder and delete the files gradlew and gradlew.bat. Also delete gradle folder Switch back to Eclipse and select Project -> Clean menu option. Fill in the form that shows up as follows: Clean Project Window Click OK and wait till the cleaning process completes Add the Java code snippet given below right after the call to setContentView function in your MainActivity class: Change the beginning of the build.gradle file till the sourceCompatibility section as follows: 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. 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. Create a new 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: HelloLambda Application 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
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) Repeatable annotations 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).
Yes, Android Supports Java 8 Now (24.1.17) Now it is possible But you will need to have your device rom run on java 1.8 and enable "jackOptions" to run it. Jack is the name for the new Android compiler that runs Java 8 https://developer.android.com/guide/platform/j8-jack.html add these lines to build_gradle android { ... defaultConfig { ... jackOptions { 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.
Android uses a Java that branches off of Java 6. As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).
Native Java 8 arrives on android! Finally! remove the Retrolambda plugin and retrolambda block from each module's build.gradle file: To disable Jack and switch to the default toolchain, simply remove the jackOptions block from your module’s build.gradle file To start using supported Java 8 language features, update the Android plugin to 3.0.0 (or higher) Starting with Android Studio 3.0 , Java 8 language features are now natively supported by android: 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); Also from min API level 24 the following Java 8 API are available: 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: 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.properties file: android.enableDesugar=false You’re done! You can now use native java8!
Android OFFICIALLY supports Java 8 as of Android N. Feature announcements are here, the Java 8 language announcement is: 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.
We Can Use Java 8 using: 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 }
UPDATE 2020/01/17 Android Studio 4.0 includes support for using a number of Java 8 language APIs, by using technique called desugaring, without requiring a minimum API level for your app: 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' } ORIGINAL POST FROM 2017 Android Studio 3.0 started to provide built-in support for some of Java 8 language features, which are: Lambda expressions Method references Type Annotations (information is available at compile time, but not at runtime) Repeating annotations Default and static interface methods Also starting from API level 24 the following Java 8 API are available: java.util.stream java.util.function java.lang.FunctionalInterface java.lang.annotation.Repeatable java.lang.reflect.AnnotatedElement.getAnnotationsByType(Class) java.lang.reflect.Method.isDefault() Besides that, the try-with-resources support was extended to all Android API levels. More Java 8 features are promised to be added in the future. To start using supported Java 8 language features, update the Android plugin to 3.0.0-alpha1 (or higher) and add the following to your module’s build.gradle file: android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } For more details visit: https://developer.android.com/studio/write/java8-support.html
Easy way You can enable java 1.8 support for android project. Open Project Structure Either by pressing Ctrl + Shift + Alt + S Or File > Project Structure Update the Source Compatibility and Target Compatibility to 1.8 in the Project Structure dialog as shown (click File > Project Structure). Or you can use gradle android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } Sync project. And that's it! Note: Java 1.8 support can be enabled for Android Studio 3.0.0 or higher. See Documentation for further reading.
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. 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. Today Kotlin reached 1.0.0. For those not familiar with Kotlin, more info can be found at their website found here: https://kotlinlang.org or watch this utube video of a talk given by Jake Wharton https://www.youtube.com/watch?v=A2LukgT2mKc
Latest news: Google announce that with Android N and Android Studio 2.1+, platform will support Java 8. Also stable version of studio 2.1 was released. At last we can use lambda expressions. No more list filter in for loop. Horeeey.
Add this config build.gradle and sync gradle: android { ... defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 // or //sourceCompatibility 1.8 //targetCompatibility 1.8 } }
Google just announced that Java 8 will be natively support by Android and that the Jack toolchain will deprecate: We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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. More Info here: https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html
Yes. We will use Java 8 soon! We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack 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. https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html
addd this line into module lvl build gradel compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
UPDATE 2019/10/28 Android Studio 4.0 solves this issue. The D8 compiler patches a backport of the Java 8 native APIs into your APK at compile time and your app will use that code, instead of the native APIs, at runtime. The process is called desugaring.
I wrote a similar answer to a similar question on Stack Overflow, but here is part of that answer. Android Studio 2.1: The new version of Android Studio (2.1) has support for Java 8 features. Here is an extract from the Android Developers blogspot post: ... Android Studio 2.1 release includes support for the new Jack compiler and support for Java 8. ... To use Java 8 language features when developing with the N Developer Preview, you need to use the Jack compiler. The New Project Wizard [File→ New→ Project] generates the correct configurations for projects targeting the N. Prior to Android Studio 2.1: Android does not support Java 1.8 yet (it only supports up to 1.7), so you cannot use Java 8 features like lambdas. This answer gives more detail on Android Studio's compatibility; it states: If you want to use lambdas, one of the major features of Java 8 in Android, you can use gradle-retrolamba If you want to know more about using gradle-retrolambda, this answer gives a lot of detail on doing that.
I figured I would post an updated answer for those looking at for something a little more current. Currently Android and Android Studio are supporting a subset of Java 8 features. According to the Android documentation located on their website, Google says: 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) Additionally, the following Java 8 language APIs are also available: 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)
I asked this question over 3 years ago and obviously the answers have changed over the years. As many above have already answered, as of sometime back, the answer became Yes. I have never updated the accepted answer because it was the correct answer at the time. (I am not sure what the Stack Overflow policy is on that) I just wanted to add another answer for those who still search for this topic. As of 5/17/2017 Google also announced that Kotlin is also an official language for Android development. I have not found an official press release, but I did watch some of the Google I/O videos where it was announced. Here is a link to a blog post by the Kotlin team on the announcement.
Adding the following fixed the problem for me (Android studio 2.3.2): build.gradle (Project) buildscript { repositories { ... jcenter() } dependencies { ... classpath 'me.tatarka:gradle-retrolambda:3.4.0' // DEPENDENCY ... } } build.gradle (Module: 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 ... }
A subset of Java 8 is supported now on Android Studio. Just make the Source and Target Compatibility adjustments from the window below: File --> Project Structure More information is given in the below link. https://developer.android.com/studio/write/java8-support.html
Easiest way to add Java 8 support compileOptions { targetCompatibility = '1.8' sourceCompatibility = '1.8' } Just add it in your build.gradle file.
Android Gradle plugin 3.0.0 and later support all Java 7 language features and a subset of Java 8 language features that vary by platform version. When building your app using Android Gradle plugin 4.0.0 and higher, you can use a number of Java 8 language APIs without requiring a minimum API level for your app. This page describes the Java 8 language features you can use, how to properly configure your project to use them, and any known issues you may encounter. For this article will help you. I'll put the link here below down https://developer.android.com/studio/write/java8-support
All the above solutions doesn't seem to work in 2019 with the latest Android Studio 3.4+. I figured out a perfect and up to date solution to migrate or upgrade your Android Project to Java 8. Solution: Click on File -> Project Structure -> Modules -> Properties tab. Change the Source Compatibility and Target Compatibility to 1.8 (Java 8)
Yes, you can use Java 8 Language features in Android Studio but the version must be 3.0 or higher. Read this article for how to use java 8 features in the android studio. https://bijay-budhathoki.blogspot.com/2020/01/use-java-8-language-features-in-android-studio.html
EASY TO REMEMBER ANSWER In android studio click on project structure icon then go inside Modules/app then change Source Compatibility and Target Compatibility to 1.8 and press Ok.
Source/Target compatibility list in Android Studio
I am in the process of updating my Android studio, Android build tools, gradle version and JDK version. Trying to switch to JDK 1.8 I am wondering why the list in the Android Studio dropdowns for "Target compatibility" and "Source compatibilty" (in the module settings) only contain the values 1.6 and 1.7. Does this mean I forgot to install/update anything or forgot to change some path? I know I can enter 1.8 manually, but the question is whether the missing 1.8 value means my setup might be incorrect?
Source and target compatibility has nothing to do with installed JDK. Your source code will still be compiled to Java 6/7/8 byte code which is used by Android. (Someone in comments, please point out technical inaccuracies, thanks.) Source and target compatibility affects language constructs you can use in source code. E.g. when targeting Java 6 you can't use the diamond operator, when targeting Java 7 you can't use lambdas, etc. Android Studio 3.0 and accompanying build plugin for Gradle (currently in development) will support Java 8 syntax out-of-the-box. Until then you could use retrolambda. Or straight up switch to Kotlin. And of course then you'll need at least JDK 8 to target Java 8.
Which JDK version (Language Level) is required for Android Studio?
I am a new comer to the android world and with a .NET background. I am trying to install the Android Studio but I am having a mismatch on Android.com about the JDK version required for developing Android applications. From the SDK web page it states that JDK 6 is required (under system requirements section). Jim Wilson also insist in his course on Pluralsight (which is quite new, from last May) that using version 7 with the Android SDK will create a lot of headache and makes it clear to only use JDK 6. Although in the Android studio page (Under installing step 2) they explain how to set an environment variable indicating the correct JDK location. In here they use a path of JDK 7 Select Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and add a new system variable JAVA_HOME that points to your JDK folder, for example C:\Program Files\Java\jdk1.7.0_21. I am pretty sure both the ADT & Eclipse bundle and the Android Studio bundle are using the same SDK but now I am confused about which JDK version I need to install. My sole purpose is to avoid problems as much as possible while getting my first steps into the Android development. Disclaimer: I am not related by any mean to Pluralsight. I am just a normal user following the courses.
Answer Clarification - Android Studio supports JDK8 The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful. Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16). Java 8 update (3/19/14) Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8. Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/ If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising. Another Update: Android added Java 7 support Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle: android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } Older response I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below. What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine. Update: See this SO post -- https://stackoverflow.com/a/9567402/413254
Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.
Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago. I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...
Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8 Reference: https://developer.android.com/studio/releases/index.html
Java 7 language features with Android
Just wondering if anyone has tried using new Java 7 language features with Android? I know that Android reads the bytecode that Java spits out and turns it to dex. So I guess my question is can it understand the bytecode of Java 7?
If you are using Android Studio, the Java 7 language should be enabled automatically without any patches. Try-with-resource requires API Level 19+, and NIO 2.0 stuff are missing. If you can't use Java 7 features, see #Nuno's answer on how to edit your build.gradle. The following is for historical interest only. A small part of Java 7 can certainly be used with Android (note: I have only tested on 4.1). First of all, you could not use Eclipse's ADT because it is hard-coded that only Java compiler 1.5 and 1.6 are compliant. You could recompile ADT but I find there is no simple way to do that aside from recompiling the whole Android together. But you don't need to use Eclipse. For instance, Android Studio 0.3.2, IntelliJ IDEA CE and other javac-based IDEs supports compiling to Android and you could set the compliance even up to Java 8 with: File → Project Structure → Modules → (pick the module at the 2nd pane) → Language level → (choose "7.0 - Diamonds, ARM, multi-catch, etc.") This only allows Java 7 language features, and you can hardly benefit from anything since a half of improvement also comes from the library. Features you could use are those which do not depend on the library: Diamond operator (<>) String switch Multiple-catch (catch (Exc1 | Exc2 e)) Underscore in number literals (1_234_567) Binary literals (0b1110111) And these features cannot be used yet: The try-with-resources statement — because it requires the non-existing interface "java.lang.AutoCloseable" (this can be used publicly in 4.4+) The #SafeVarargs annotation — because "java.lang.SafeVarargs" does not exist ... "yet" :) It turns out that, although Android's library is targeting for 1.6, the Android source does contain interfaces like AutoCloseable and traditional interfaces like Closeable does inherit from AutoCloseable (SafeVarargs is really missing, though). We could confirm its existence via reflection. They are hidden simply because the Javadoc has the #hide tag, which caused the "android.jar" not to include them. There is already as existing question How do I build the Android SDK with hidden and internal APIs available? on how to get those methods back. You just need to replace the existing "android.jar" reference of the current Platform with our customized one, then many of the Java 7 APIs will become available (the procedure is similar to that in Eclipse. Check Project Structure → SDKs.) In additional to AutoCloseable, (only) the following Java 7 library features are also revealed: Exception chaining constructors in ConcurrentModificationException, LinkageError and AssertionError The static .compare() methods for primitives: Boolean.compare(), Byte.compare(), Short.compare(), Character.compare(), Integer.compare(), Long.compare(). Currency: .getAvailableCurrencies(), .getDisplayName() (but without .getNumericCode()) BitSet: .previousSetBit(), .previousClearBit(), .valueOf(), .toLongArray(), .toByteArray() Collections: .emptyEnumeration(), .emptyIterator(), .emptyListIterator() AutoCloseable Throwable: .addSuppressed(), .getSuppressed(), and the 4-argument constructor Character: .compare(), .isSurrogate(), .getName(), .highSurrogate(), .lowSurrogate(), .isBmpCodePoint() (but without .isAlphabetic() and .isIdeographic()) System: .lineSeparator() (undocumented?) java.lang.reflect.Modifier: .classModifiers(), .constructorModifiers(), .fieldModifiers(), .interfaceModifiers(), .methodModifiers() NetworkInterface: .getIndex(), .getByIndex() InetSocketAddress: .getHostString() InetAddress: .getLoopbackAddress() Logger: .getGlobal() ConcurrentLinkedDeque AbstractQueuedSynchronizer: .hasQueuedPredecessors() DeflaterOutputStream: the 3 constructors with "syncFlush". Deflater: .NO_FLUSH, .SYNC_FLUSH, .FULL_FLUSH, .deflate() with 4 arguments That's basically all. In particular, NIO 2.0 does not exist, and Arrays.asList is still not #SafeVarargs.
EDIT: At the time this was written, the latest release was Android 9 and Eclipse Indigo. Thing have changed since then. Practical answer Yes, I have tried. But this is not a great test as the compatibility was limited to level 6 with no way (no simple way at least) to really use java 7: First I installed a JDK7 on a machine that had no other JDK installed - Eclipse and Android are not installed either: Then I installed a brand new Eclipse Indigo and checked it was actually using the JDK 7 (well, as this is the only one and as this is the one I've selected I would have been surprised) Then I installed the latest version of the Android SDK (EDIT: Honeycomb, API13, at the time this post was written). It found my JDK 7 and installed properly. The same for ADT. But I had a surprise when trying to compile and run a Hello Word Android app. The compatibility was set to Java 6 with no way to force it to Java 7: I tried with a non-Android project, a regular Java one, and I had the explanation. The compatibility level seems to be limited by Eclipse (see the message at bottom of the following image): So I had Hello World working, and also other apps, more complicated and using SQLite, Listview, Sensor and Camera, but this only proves that the compatibility handling of Java 7 seems to be well done and working with Android. So, did someone try with the good old Ant, to bypass the Eclipse limitation seen above? Theroetical answer Anyway, the SDK is designed to be used with Java 5 or 6, as explained here. We may have something working with Java 7, but it would be working "by accident". The building of the DEX may work properly or not, and once the DEX built, it may work or not. This because using a non-qualified JDK gives unpredictable results by definition. Even if someone has succesfully built an Android app under plain Java 7, this does not qualify the JDK. The same process applied to another application may fail, or the resulting application may have bugs tied to the use of that JDK. Not recommended. For those who are involved on webapps development, this exactly the same as deploying a web application built under Java 5 or 6 under an application server qualified for Java 4 only (let's say Weblogic 8 for example). This may work, but this is not something that can be recommended for other purposes than trying.
Quote from dalvikvm.com: dx, included in the Android SDK, transforms the Java Class files of Java classes compiled by a regular Java compiler into another class file format (the .dex format) That means, the .java source file does not matter, it's only the .class bytecode. As far as I know, only invokedynamic was added to the JVM bytecode in Java 7, the rest is compatible to Java 6. The Java language itself does not use invokedynamic. Other new features, like the switch statement using Strings or the multi-catch are just syntatic sugar and did not require byte code changes. For example, the multi-catch just copies the catch-block for each possible exception. The only problem should be that the new classes introduced in Java 7 are missing in Android, like AutoCloseable, so I'm not sure if you can use the try-with-resources feature (somebody tried it?). Any comments on that? Am I missing something?
As of the Android SDK v15, along with Eclipse 3.7.1, Java 7 is not supported for Android development. Setting the source compatibility to 1.7 mandates setting the generated .class file compatibility to 1.7, which leads to the following error by the Android compiler: Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties.
To expand on the above answer by #KennyTM, if you are targeting 4.0.3 and above (minSdkVersion=15), you can use the hidden APIs by adding a few classes to your target's SDK android.jar. Once you do this, you can use try-with-resources on any Closeable, as well as implement AutoCloseable in your own classes. I've made a zip containing sources and binaries of all the classes that needed to be modified in android.jar to make these APIs available. You just need to unpack it and add the binaries to your android-sdk/platforms/android-NN/android.jar You can download it from here: http://db.tt/kLxAYWbr Also of note is that, in the past couple of months, Elliott Hughes has made a few commits to the Android tree: finished off AutoCloseable, added SafeVarargs, unhidden various APIs, fixed Throwable's protected constructor and added support for version 51 class files in dx. So, there is finally some progress going on. Edit (April 2014): With the release of SDK 19 it is no longer necessary to patch android.jar with the additional APIs. The best method to use try-with-resources in Android Studio for an app that targets 4.0.3 and above (minSdkVersion=15) is add the following compileOptions to your build.gradle: android { compileSdkVersion 19 buildToolsVersion '19.0.3' defaultConfig { minSdkVersion 15 targetSdkVersion 19 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } Android Studio will complain that try-with-resources can't be used with this API level, but my experience is that it can. The project will build and run without issue on devices with 4.0.3 and above. I've experienced no issues with this, with an app that has been installed into 500k+ devices. To ignore this warning, add the following to your lint.xml: <issue id="NewApi"> <ignore regexp="Try-with-resources requires API level 19"/> </issue>
It seems that getting this to work with pure ant is a bit of a kludge. But it worked for me: http://www.informit.com/articles/article.aspx?p=1966024
In order to use Java 7 features in code build by Android's ant based build system, simply put the following in your custom_rules.xml in your projects root directory: custom_rules.xml: <project name="custom_android_rules"> <property name="java.target" value="1.7" /> <property name="java.source" value="1.7" /> </project>
Some people might be interested in this git project I've found, that seems to allow to run Java 7 on android. https://github.com/yareally/Java7-on-Android However too much of a risk if I add this in the current project I work on. So I'll wait until Google to officially support Java 7.