讓Android studio支持java8

一:只須要支持Lambda表達式

在app/build.gradle下添加html

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();
  •  

二:Java 8和Jack編譯

參考Android官網android

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.app

開啓jack編譯後,不能使用apt插件,報異常:Error:Could not find property ‘options’ on task ‘:app:compileDebugJavaWithJack’.參考:google issuesmaven

補充

能夠使用annotationProcessor代替apt插件,以後便可使用jack編譯 
官方原文gradle

相關文章
相關標籤/搜索