Java 8 development with Android Studio 3.0 -Part 1

Java 8 Development using Android Studio :

Using Android Studio 3.0 preview 1 and later, some subset of Java 8 language features can be used on Android projects. Some features are compatible with all API levels and some are only for API level 24 and higher. Previously for using Java8 on Android projects, jack toolchain, Retrolambda or DexGuard was used. Jack toolchain is now deprecated ( check this  post ) and the Java 8 support is moved to the default keychain. You can still use Jack or other libraries but it is advisable to migrate to the default toolchain.

Migration :

If you have a project with Jack, Retrolambda or DexGuard using Java 8, it will still work but if you want to move to default toolchain, check out below :

Migrate from Jack Toolchain :

To disable Jack Toolchain and for using the default one, remove the jackOptions block from build.gradle file :

android {
    ...
    defaultConfig {
        ...
        // Remove below jackOptions{...} block.
        jackOptions {
            enabled true
            ...
        }
    }

Migrate from Retrolambda :

For removing Retrolambda, you need to remove its dependency and “retrolambda” block from project-level and module’s build.gradle file :
Remove the below dependency line :

classpath 'me.tatarka:gradle-retrolambda:’

Remove ‘retrolambda’ block and plugin declaration:

// remove the below line 
apply plugin: 'me.tatarka.retrolambda'

// Remove this block 
retrolambda {
    ...
    // If you have arguments for the Java VM you want to keep,
    // move them to your project's gradle.properties file.
    jvmArgs '-Xmx2048m'
}

Configure Android Studio :

Change “dependencies” tab of project level “build.gradle” file to use Android plugin 3.0.0-alpha1 or higher :

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha7’
}

Add the following block inside android{} of build.gradle file :

android{
    ….
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

What Java 8 language features and APIs you can use with Android Studio 3.0 :

You can visit the official page  for detail info , but common operations like Lambda expressions, Method references, Type Annotations are supported on all versions with some restrictions. We will look into details on next tutorials.

Disable support :

If you are facing some trouble while using Java 8 features with Android Studio, you can disable them by adding the following line to your gradle.properties file :

android.enableDesugar=false

No Comments

Post a Comment