1. 程式人生 > >讓Android studio支援java8

讓Android studio支援java8

一:只需要支援Lambda表示式

在app/build.gradle下新增

android {
    //設定JDK1.8
    compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
}
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'me.tatarka:gradle-retrolambda:3.2.5'
} } repositories { mavenCentral() } //新增外掛 apply plugin: 'me.tatarka.retrolambda'

然後就可以使用Lambda表示式了,比如

new Thread(new Runnable() {
    public void run() {
      System.out.println("Run!");
    }
  }).start();

可以簡化成

new Thread(() ->System.out.println("Run!")).start();

Github

二:Java 8和Jack編譯

android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

注意: 需要使用Android N 也就是API24,以下是官方原話:
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.

開啟jack編譯後,不能使用apt外掛,報異常:Error:Could not find property ‘options’ on task ‘:app:compileDebugJavaWithJack’.參考:google issues

補充

可以使用annotationProcessor代替apt外掛,之後即可使用jack編譯
官方原文