SlideShare a Scribd company logo
1 of 42
Download to read offline
Jorge Castillo
www.twitter.com/JorgeCastilloPr
www.github.com/JorgeCastilloPrz
jorge.castillo.prz@gmail.com
Developing Android apps with Java 8
About us
Candidates Companies
Our Android team Still hiring!
karumi.com
Android N Preview recently published
Java 8 appeared in the spotlight
Two new tools added to The SDK
● Jack compiler (Java Android Compiler Kit)
● Jill (Jack Intermediate Library Linker)
● 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'
}
Jack
Java
source files
Dex files
Shrinking
Repackaging
Obfuscation
Multidex
Jack
What about libraries? (.jar, .aar, .apklib)
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)
APK
Predexing
● 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
Okay but, how do I use the new tools ?
Let’s calm down (vamo a calmarno.)
● 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'
}
}
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
Java 8
Supported features
● 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
Interfaces - Default methods
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();
}
● 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
Interfaces - Static methods
● I would use them for utility methods tied to the contract
Interfaces - Static methods
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;
}
}
Lambdas
● 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
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)
What if multiple args needed?
Functional Interfaces
● Provide target types for lambda expressions and method references
● Java 8 gives you some of them out of the box
Functional interfaces
Interfaces - Static methods
● 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;
};
Method references
● Compact, easy-to-read lambda expressions for methods that
already exist
● 4 different types
Method references
// 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);
Repeatable annotations
● There are some situations where you want to apply the same
annotation to a declaration or type use.
Repeatable annotations
Streams
● 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<>();
● 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
?

More Related Content

What's hot (20)

Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Kotlin
KotlinKotlin
Kotlin
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Runtime
RuntimeRuntime
Runtime
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 

Similar to Developing android apps with java 8

Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Simon Ritter
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014Nayden Gochev
 

Similar to Developing android apps with java 8 (20)

Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Spring 3 to 4
Spring 3 to 4Spring 3 to 4
Spring 3 to 4
 
Java se7 features
Java se7 featuresJava se7 features
Java se7 features
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3Lambdas and-streams-s ritter-v3
Lambdas and-streams-s ritter-v3
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Developing android apps with java 8

  • 4. Our Android team Still hiring! karumi.com
  • 5. Android N Preview recently published
  • 6. Java 8 appeared in the spotlight
  • 7. Two new tools added to The SDK ● Jack compiler (Java Android Compiler Kit) ● Jill (Jack Intermediate Library Linker)
  • 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' }
  • 10. What about libraries? (.jar, .aar, .apklib)
  • 11. 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)
  • 13. ● 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
  • 14. Okay but, how do I use the new tools ? Let’s calm down (vamo a calmarno.)
  • 15. ● 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' } }
  • 16. 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
  • 19. ● 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
  • 21. 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(); }
  • 22. ● 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
  • 24. ● I would use them for utility methods tied to the contract Interfaces - Static methods
  • 25. 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; } }
  • 27. ● 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
  • 28. 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)
  • 29. What if multiple args needed?
  • 31. ● Provide target types for lambda expressions and method references ● Java 8 gives you some of them out of the box Functional interfaces
  • 33. ● 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; };
  • 35. ● Compact, easy-to-read lambda expressions for methods that already exist ● 4 different types Method references
  • 36. // 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);
  • 38. ● There are some situations where you want to apply the same annotation to a declaration or type use. Repeatable annotations
  • 40. ● 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<>();
  • 41. ● 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
  • 42. ?