42
Jorge Castillo www.twitter.com/JorgeCastilloPr www.github.com/JorgeCastilloPrz [email protected] Developing Android apps with Java 8

Developing android apps with java 8

Embed Size (px)

Citation preview

Page 2: Developing android apps with java 8

About us

Page 3: Developing android apps with java 8

Candidates Companies

Page 4: Developing android apps with java 8

Our Android team Still hiring!

karumi.com

Page 5: Developing android apps with java 8

Android N Preview recently published

Page 6: Developing android apps with java 8

Java 8 appeared in the spotlight

Page 7: Developing android apps with java 8

Two new tools added to The SDK

● Jack compiler (Java Android Compiler Kit)

● Jill (Jack Intermediate Library Linker)

Page 8: Developing android apps with java 8

● Compiles Java sources directly into DEX bytecode

● Improves build times (pre-dexing, incremental compilation)

● Handles shrinking, obfuscation, repackaging and multidex

● Executes annotation processors

Jack

dependencies { compile 'com.google.dagger:dagger:2.5' compile 'com.jakewharton:butterknife:8.1.0'

annotationProcessor 'com.jakewharton:butterknife-compiler:8.1.0' annotationProcessor 'com.google.dagger:dagger-compiler:2.5'}

Page 9: Developing android apps with java 8

JackJava

source filesDex files

Shrinking

Repackaging

Obfuscation

Multidex

Jack

Page 10: Developing android apps with java 8

What about libraries? (.jar, .aar, .apklib)

Page 11: Developing android apps with java 8

Jill

Jayce

Jack

Extract Res

● Translate library dependencies to Jack format (.jack)

● Prepares them to be quickly merged with other .jack files

Select Res Resourcesdirectory

JACK used to generate a pre-dexed library

Jayce

Pre-dex

Res

.jack

.class

res

.jar

Jill (Jack Intermediate library linker)

Page 12: Developing android apps with java 8

APK

Predexing

Page 13: Developing android apps with java 8

● No more .class intermediate step in toolchain:

○ Bytecode manipulation tools based on .class files (like JaCoCo)

are not working anymore.

○ Lint detectors based on .class file analysis not working anymore.

● Java 8 just supported on versions >= N (API 24)*

Limitations

Page 14: Developing android apps with java 8

Okay but, how do I use the new tools ?

Let’s calm down (vamo a calmarno.)

Page 15: Developing android apps with java 8

● For new projects: File -> New project -> pick Android N

● For already started projects: Add this to your root build.gradle:

buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.0-alpha4' }}

Page 16: Developing android apps with java 8

android {

compileSdkVersion 24 buildToolsVersion "24.0.0"

defaultConfig { applicationId "com.github.jorgecastillo.java8testproject" minSdkVersion 9 targetSdkVersion 24

jackOptions { enabled true } }

compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }

app build.gradle

Page 17: Developing android apps with java 8

Java 8

Page 18: Developing android apps with java 8

Supported features

Page 19: Developing android apps with java 8

● Default and static interface methods

● Lambdas

● Functional Interfaces

● Method references

● Repeatable annotations

● Some new reflection methods such as AnnotatedElement.getAnnotationsByType(Class)

● Streams

● Optionals

minSdkVersion 24 minSdkVersion 9

● Lambdas

● Functional Interfaces (not the ones out of the box from the JDK 8)

● Method references

● Repeatable annotations

Page 20: Developing android apps with java 8

Interfaces - Default methods

Page 21: Developing android apps with java 8

public interface DiscoverMoviesPresenter extends DiscoverMovies.Callback {

default void discoverMovies(SortingOption sortingOption) { getLoadingView().showLoading(); getDiscoverMoviesUseCase().execute(sortingOption, this);

}

@Override default void onSuccess(List<Movie> movies) { getLoadingView().hideLoading(); getMovieListView().renderMovies(movies);

}

@Override default void onError(String message) { getLoadingView().hideLoading(); getMovieListView().displayRenderMoviesError(message);

}

LoadingView getLoadingView();

MovieListView getMovieListView();

DiscoverMovies getDiscoverMoviesUseCase();}

Page 22: Developing android apps with java 8

● They make Java 8 interfaces very similar to Traits or rich interfaces

from other modern languages

● They allow developers to compose class behavior based on multiple

interfaces

● Interfaces cannot store state

Interfaces - Default methods

Page 23: Developing android apps with java 8

Interfaces - Static methods

Page 24: Developing android apps with java 8

● I would use them for utility methods tied to the contract

Interfaces - Static methods

Page 25: Developing android apps with java 8

public interface TimeMachine {

void goToTime(int hour, int minute, int seconds);

void goToDate(int day, int month, int year);

Long getCurrentTime();

Date getCurrentDate();

default ZonedDateTime getZonedDateTime(String zoneString) { return new ZonedDateTime(getCurrentTime(), getZoneId(zoneString)); }

static Long getZoneId(String zoneString) { // ... return 10L;

}}

Page 26: Developing android apps with java 8

Lambdas

Page 27: Developing android apps with java 8

● Literal representation of a function

● As in other modern languages: input args -> function body

● Assignable to variables

● Being passed as method arguments and returned as return values

(High order functions)

● First class citizen

● Translated to anonymous classes for lower API versions

Lambdas

Page 28: Developing android apps with java 8

Lambda declaration

private List<Movie> validMovies( List<Movie> movies, Function<Movie, Boolean> isValid) {

return movies.stream().filter(isValid::apply) .collect(Collectors.toList());}

Function<Movie, Boolean> isValid = movie -> movie.getId() % 2 == 0;

validMovies(movies, isValid);

validMovies(movies, movie -> movie.getId() % 2 == 0); (inline)

Page 29: Developing android apps with java 8

What if multiple args needed?

Page 30: Developing android apps with java 8

Functional Interfaces

Page 31: Developing android apps with java 8

● Provide target types for lambda expressions and method references

● Java 8 gives you some of them out of the box

Functional interfaces

Page 32: Developing android apps with java 8

Interfaces - Static methods

Page 33: Developing android apps with java 8

● Custom functional interface for lambdas with 3 input arguments

@FunctionalInterface public interface Function3<A, B, C, R> {

R apply(A a, B b, C c);}

Function3<Long, Integer, Boolean, Boolean> isEven = (l, i, b) -> l % 2 == 0;

● Use it

Function3<Long, Integer, Boolean, Boolean> isEven2 = (l, i, b) -> { return l % 2 == 0;};

Page 34: Developing android apps with java 8

Method references

Page 35: Developing android apps with java 8

● Compact, easy-to-read lambda expressions for methods that

already exist

● 4 different types

Method references

Page 36: Developing android apps with java 8

// static method referenceisValid(User::isYoung);

// instance method referenceisValid(user::isOld);

String[] stringArray = {"Barbara", "James", "Ipolito", "Mary", "John"};

// Instance method reference of arbitrary type // (string1.compareToIgnoreCase(string2))Arrays.sort(stringArray, String::compareToIgnoreCase);

// Constructor method referencegenerateUsers(User::new);

Page 37: Developing android apps with java 8

Repeatable annotations

Page 38: Developing android apps with java 8

● There are some situations where you want to apply the same

annotation to a declaration or type use.

Repeatable annotations

Page 39: Developing android apps with java 8

Streams

Page 40: Developing android apps with java 8

● Very powerful concept available in many languages

● You can extract the stream from any collection

● flatMap(), reduce(), count(), distinct(), forEach(), max(), min(), sorted(comparator) ...

Streams

users.stream() .filter(user -> user.getAvatarUrl() != null) .map(User::getAvatarUrl) .findFirst() .orElse("http://anyimage.com/fallback_avatar.png");

String avatar =

List<User> users = new ArrayList<>();

Page 41: Developing android apps with java 8

● Jack & Jill

○ Jack documentation https://source.android.com/source/jack.html

○ More details http://android-developers.blogspot.com.es/2014/12/hello-world-meet-our-new-

experimental.html

○ Annotation Processing open issue https://code.google.com/p/android/issues/detail?id=204065

● Java 8 in Android N

○ Supported features with links to documentation http://developer.android.com/preview/j8-jack.html

○ Functional Interfaces out of the box https://docs.oracle.

com/javase/8/docs/api/java/util/function/package-summary.html

Bibliography

Page 42: Developing android apps with java 8

?