Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle Android Project with Java 8 module

As I've seen in this post, Java 8 is not officially supported by Android right now. So I'm interested if it is possible to build Android module with Java 7 and Java module (as a dependency) with Java 8.

As an example, I'm trying to create a Gradle project that will contain one Android module and one Java module as a dependency. With the following compileOptions set for both modules, everything works fine.

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

But if I try to change compileOptions for my Java module to

compileJava {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}

I get the following error:

Error:Execution failed for task ':fc-android:preDexFreeDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_45\bin\java.exe'' finished with non-zero exit value 1

So the question, is that actually possible to have Android module compiled with 1.7 version and dependent Java module compiled with 1.8? And if not, so why?

UPDATE:

Retrolamba for Gradle (mentioned by @Saeed) is good, however they have only support of lambdas, so not access to Stream API, DateTime API and other features. Imagine if we have *.jar file built with Java 8 (no Android code). I think that we can't use such *.jar file as a dependency for Android module, because it's bytecode will not be supported by ART or Dalvik, but only by JVM for Java 8.

like image 817
Yuriy Yunikov Avatar asked Jun 04 '15 19:06

Yuriy Yunikov


1 Answers

Android can support java 1.7 since API 19 (as you see in this doc there is no mention of java 1.8) and also it doesn't use JVM and using ART or Dalvik instead ,So it generates Dalvik bytecode.

I think if we want to use java 1.8 as compileOptions maybe android run time can't understand some new features in java 8 like lambda so gradle doesn't allow you to compile your code and you got that exception.

So you need a bytecode transformer to use

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

Read this tutorial .It converts your bytecodes to be compatible with java 7.I've tested this before and it works for me.

Update 2016

Android N introduces support for Java 8 language features.

like image 160
Saeed Masoumi Avatar answered Sep 23 '22 06:09

Saeed Masoumi