Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Developing Android apps with Java 8

Developing Android apps with Java 8

Google has recently released a preview version of Android N, and brand new Java 8 features appeared around. They gave us a sneak peak about the future of Android development.

In this talk we are going to showcase all the supported new language features up to date, detailing which ones are retrocompatible and which ones will just be available starting on API 24 (N). We will get our hands on a Clean Architecture sample project which will use java 8 functionalities on its diffent layers, in order to make people think a little bit more about how those new language features can become handy for us to simplify our code and project architecture.

Jorge Castillo

July 09, 2016
Tweet

More Decks by Jorge Castillo

Other Decks in Programming

Transcript

  1. Two new tools added to The SDK • Jack compiler

    (Java Android Compiler Kit) • Jill (Jack Intermediate Library Linker)
  2. • 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' }
  3. Jill Jayce Jack Extract Res • Translate library dependencies to

    Jack format (.jack) • Prepares them to be quickly merged with other .jack files Select Res Resources directory JACK used to generate a pre-dexed library Jayce Pre-dex Res .jack .class res .jar Jill (Jack Intermediate library linker)
  4. • 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
  5. Okay but, how do I use the new tools ?

    Let’s calm down (vamo a calmarno.)
  6. • 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' } }
  7. 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
  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
  9. 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(); }
  10. • 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
  11. • I would use them for utility methods tied to

    the contract Interfaces - Static methods
  12. 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; } }
  13. • 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
  14. 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)
  15. • Provide target types for lambda expressions and method references

    • Java 8 gives you some of them out of the box Functional interfaces
  16. • 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; };
  17. // static method reference isValid(User::isYoung); // instance method reference isValid(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 reference generateUsers(User::new);
  18. • There are some situations where you want to apply

    the same annotation to a declaration or type use. Repeatable annotations
  19. • 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<>();
  20. • 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
  21. ?