SlideShare a Scribd company logo
1 of 42
Android
Architecture
Presentation by:
Bui Trong An
Trip Application
Email: trongan93@gmail.com
Skype: trongan93
Reference:
Technical Uber http://t.uber.com
Google Dagger2 - https://google.github.io/dagger
Dependency Injection
Audience Prerequisites
You know how to write a basic Android App
Nice to have:
You’re familiar with ButterKnife
You’ve written a fairly large or growing Andorid App
You’ve configured and used networking stacks,
imaging libraries, persistent data...
Wikipedia
Dependency injection is a software design pattern in which
one or more dependencies (or services) are injected, or
passed by reference, into a dependent object (or client)
and are made part of the client's state. The pattern
separates the creation of a client's dependencies from its
own behavior, which allows program designs to be loosely
coupled and to follow the dependency inversion and single
responsibility principles.
Goal of this presentation
To explain the reasons and concepts behind
Dependency Injection, specifically Dagger 2 in
in the context of Android.
To understand the big picture so you’ll know
where to look for the answers.
TL;DR
Separation of Configuration & Usage
Maintainability, testability, mockability, low
coupling, easy singletons, less boilerplate*
Configuration vs Usage
SharedPreferences
Image Loader
(Picasso)
Network Client
(OkHttp)
API Interface
(Retrofit)
Http Disk Cache
Image Disk Cache
SessionManager
(Auth tokens)
Activities
Fragments
Views
Objects
Extremely brief history of Dagger
Dagger 1 - Square
Object Graph
Code Generation
Some Reflection
Dagger 2 - Google
Components
Code Generation
No Reflection
Usage
TextView mTitleText;
TextView mBodyText;
TextView mIconText;
// in constructor
mTitleText =
(TextView) findViewById(R.id.title)
mBodyText =
(TextView) findViewById(R.id.body)
mFooterText =
(ImageView) findViewById(R.id.icon)
Butterknife Analogy
@InjectView(R.id.title)
TextView mTitleText;
@InjectView(R.id.body)
TextView mBodyText;
@InjectView(R.id.icon)
ImageView mIcon;
// in constructor
Butterknife.inject(this, viewGroup)
TextView mTitleText;
TextView mBodyText;
TextView mIconText;
// in constructor
mTitleText =
(TextView) findViewById(R.id.title)
mBodyText =
(TextView) findViewById(R.id.body)
mFooterText =
(ImageView) findViewById(R.id.icon)
Butterknife Analogy
@InjectView(R.id.title)
TextView mTitleText;
@InjectView(R.id.body)
TextView mBodyText;
@InjectView(R.id.icon)
ImageView mIcon;
// in constructor
Butterknife.inject(this, viewGroup)
Take all fields with annotation, look in the ViewGroup and
find the view by id, cast to expected type, set field.
Butterknife Analogy
ViewGroup Object
findViewById
@InjectView
Take all fields with annotation, look in the ViewGroup and
find the view by id, cast to expected type, set field.
Configuration vs Usage
SharedPreferences
Image Loader
(Picasso)
Network Client
(OkHttp)
API Interface
(Retrofit)
Http Disk Cache
Image Disk Cache
SessionManager
(Auth tokens)
Activities
Fragments
Views
Objects
@Inject
Dagger Usage
Component Object
“find object
by type”
@Inject
Take all fields with annotation, look in the Component
and find the object by type (or create it), and set the field.
FKA ObjectGraph
Dagger Usage
@Inject Picasso mPicasso;
@Inject SessionManager mSessionManager;
@Inject Toolbar mToolbar;
@Inject UberApi mUberApi;
// in onCreate()
getComponent().inject(this);
Take all fields with annotation, look in the Component
and find the object by type (or create it), and set the field.
Where do we get the Component?
public class MyApp extends Application {
private MyAppComponent component;
@Override public void onCreate() {
component = ???
}
public MyAppComponent getComponent() {
return component;
}
}
<application
android:name=".MyApp"
…>
<activity … />
</application>
AndroidManifest.xml MyApp.java
public MyComponent getComponent() { return component; }
Where do we get the Component?
MyApp.java
((MyApp) this.getApplicationContext()).getComponent().inject(this);
MyActivity.java
MyApp.get(this).getComponent().inject(this);
MyActivity.java
public static MyApp get(Context context) {
return ((MyApp) context.getApplicationContext());
}
public MyComponent getComponent() { return component; }
Where do we get the Component?
MyApp.java
public static MyComponent getComponent(Context context) {
return ((MyApp) context.getApplicationContext()).component;
}
Where do we get the Component?
MyApp.java
MyApp.getComponent(this).inject(this);
MyActivity.java
public static MyComponent getComponent(Context context) {
return ((MyApp) context.getApplicationContext()).component;
}
Where do we get the Component?
MyApp.java
MyApp.getComponent(this).inject(this);
MyActivity.java
MyApp.getComponent(getActivity()).inject(this);
MyFragment.java
Configuration
Configuration vsUsage
SharedPreferences
Image Loader
(Picasso/Universal)
Network Client
(OkHttp)
API Interface
(Retrofit)
Http Disk Cache
Image Disk Cache
SessionManager
(Auth tokens)
Activities
Fragments
Views
Objects
Modules & Components
Activities
Fragments
Views
Objects
Networking
Module
Storage
Module
Application
Module
Application
Component
.inject()
FKA ObjectGraph
“the graph”
Network Client
API Interface
Disk Cache
SharedPreferences
Application
.inject()
.inject()
Modules & More Components
Activities
Fragments
Views
Objects
Networking
Module
Storage
Module
Application
Module
Application
Component
Activity
Module
Activity
Component
Activities
Fragments
Views
Objects
FKA ObjectGraph
FKA “sub-graph”
Toolbar
Shared State
Defining a Component
@Component
public interface MyAppComponent {
void inject(MyActivity myActivity);
}
MyAppComponent.java
Actual Implementation is generated by Dagger 2.
Just an interface:
Depending on a Module
@Component(
modules = {
MyAppModule.class,
}
)
public interface MyAppComponent {
void inject(MyActivity myActivity);
}
MyAppComponent.java
Defining a Module
@Module public class MyAppModule {
private final MyApp app;
public MyAppModule(MyApp app) {
this.app = app;
}
@Provides MyApp provideMyApp() {
return app;
}
}
MyAppModule.java
Defining a Module
@Module public class MyAppModule {
private final MyApp app;
public MyAppModule(MyApp app) {
this.app = app;
}
@Provides @Singleton MyApp provideMyApp() {
return app;
}
}
MyAppModule.java
Defining a Module
@Module public class MyAppModule {
private final MyApp app;
public MyAppModule(MyApp app) {
this.app = app;
}
@Provides @PerApp MyApp provideMyApp() {
return app;
}
}
MyAppModule.java
Providing Objects
@Module public class ApiModule {
@Provides @Singleton RestAdapter provideRestAdapter(Endpoint endpoint, Client
client, Converter converter, ApiHeaders headers) {
return new RestAdapter.Builder()
.setClient(client)
.setEndpoint(endpoint)
.setConverter(converter)
.setRequestInterceptor(headers)
.setLogLevel(BuildConfig.DEBUG
? RestAdapter.LogLevel.FULL
: RestAdapter.LogLevel.NONE)
.build();
}
}
MyAppModule.java
Bringing it all together
public class MyApp extends Application {
private MyComponent component;
@Override public void onCreate() {
component = ???
}
public MyComponent getComponent() { … }
}
MyApp.java
Bringing it all together
public class MyApp extends Application {
private MyComponent component;
@Override public void onCreate() {
component = DaggerMyAppComponent.builder()
.myAppModule(new MyAppModule(this))
.build();
}
public MyComponent getComponent() { … }
}
MyApp.java
The Component Builder
@Singleton
@Component(
modules = MyAppModule.class
)
public interface MyAppComponent {
void inject(MyApp myApp);
}
DaggerMyAppComponent.builder()
.myAppModule(new MyAppModule(this))
.build();
MyAppComponent.java MyApp.java
The Component Builder
@Singleton
@Component(
modules = {
MyAppModule.class
DataModule.class,
NetworkModule.class
}
)
public interface MyAppComponent {
void inject(MyApp myApp);
}
DaggerMyAppComponent.builder()
.myAppModule(new MyAppModule(this))
.dataModule(new DataModule())
.networkModule(new NetworkModule())
.build();
MyAppComponent.java MyApp.java
Modules & Components
Activities
Fragments
Views
Objects
Networking
Module
Storage
Module
Application
Module
Application
Component
.inject()
FKA ObjectGraph
“the graph”
Network Client
API Interface
Disk Cache
SharedPreferences
Application
.inject()
.inject()
Component Dependencies
Activities
Fragments
Views
Objects
Networking
Module
Storage
Module
Application
Module
Application
Component
Activity
Module
Activity
Component
Activities
Fragments
Views
Objects
FKA ObjectGraph
FKA “sub-graph”
Toolbar
Shared State
Component Dependencies
@Component(
dependencies =
MyAppComponent.class,
modules =
MyActivityModule.class
)
public interface MyActivityComponent {
void inject(MyActivity myActivity);
}
DaggerMyAppComponent.builder()
.myAppComponent(
MyApp.getComponent(this))
.myActivityModule(
new MyActivityModule(this))
.build();
MyActivityComponent.java MyActivity.java
@Component(
dependencies = MyAppComponent.class,
modules = MyActivityModule.class
)
public interface MyActivityComponent {
void inject(MyActivity myActivity);
void inject(MyFragment myFragment);
}
Component Dependencies
DaggerMyActivityComponent.builder()
.myAppComponent(MyApp.getComponent(this))
.myActivityModule(new MyActivityModule(this))
.build();
MyActivityComponent.java
MyActivity.java
@Component(
modules = {
MyAppModule.class
}
)
public interface MyAppComponent {
void inject(MyApp myApp);
void inject(MyActivity myActivity);
MyApp myApp();
SharedPreferences sharedPrefs();
}
MyAppComponent.java
Scopes
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerApp { }
PerApp.java
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity { }
PerActivity.java
Scopes
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerApp { }
PerApp.java
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity { }
PerActivity.java
@PerApp
@Component(…)
public interface MyAppComponent {
@PerApp @Provides SharedPrefs…
@PerActivity
@Component(…)
public interface MyAactivityComponent {
@PerActivity @Provides Toolbar…
Constructor Injection
@Provides MyThing provideMyThing(
SharedPreferences sp,
Context context) {
return new MyThing(sp, context);
}
@PerApp
class MyThing {
private final SharedPRefs…
private final Context ...
@Inject public MyThing(
SharedPreferences sp,
Context context) {
}
}
Q & A
Resources
Jake Wharton’s Presentation:
http://google.github.io/dagger/
http://t.uber.com/dagger2codepath

More Related Content

What's hot

Android basic principles
Android basic principlesAndroid basic principles
Android basic principles
Henk Laracker
 
Android application development workshop day1
Android application development workshop   day1Android application development workshop   day1
Android application development workshop day1
Borhan Otour
 

What's hot (20)

Android programming basics
Android programming basicsAndroid programming basics
Android programming basics
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1
 
Android - From Zero to Hero @ DEVit 2017
Android - From Zero to Hero @ DEVit 2017Android - From Zero to Hero @ DEVit 2017
Android - From Zero to Hero @ DEVit 2017
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
Introduction to android basics
Introduction to android basicsIntroduction to android basics
Introduction to android basics
 
Arduino - Android Workshop Presentation
Arduino - Android Workshop PresentationArduino - Android Workshop Presentation
Arduino - Android Workshop Presentation
 
Ppt 2 android_basics
Ppt 2 android_basicsPpt 2 android_basics
Ppt 2 android_basics
 
Google Android
Google AndroidGoogle Android
Google Android
 
Android basic principles
Android basic principlesAndroid basic principles
Android basic principles
 
Android components
Android componentsAndroid components
Android components
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App Development
 
Android basics
Android basicsAndroid basics
Android basics
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
 
Android application development workshop day1
Android application development workshop   day1Android application development workshop   day1
Android application development workshop day1
 
Unit2
Unit2Unit2
Unit2
 
Android Applications Development
Android Applications DevelopmentAndroid Applications Development
Android Applications Development
 
Android application development for TresmaxAsia
Android application development for TresmaxAsiaAndroid application development for TresmaxAsia
Android application development for TresmaxAsia
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 

Viewers also liked

android architecture
android architectureandroid architecture
android architecture
Aashita Gupta
 
Android architecture
Android architectureAndroid architecture
Android architecture
Hari Krishna
 
Android OS Presentation
Android OS PresentationAndroid OS Presentation
Android OS Presentation
hession25819
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
connectshilpa
 
lisa.graham.rocks
lisa.graham.rockslisa.graham.rocks
lisa.graham.rocks
Lisa Graham
 

Viewers also liked (20)

android architecture
android architectureandroid architecture
android architecture
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Android Platform Architecture
Android Platform ArchitectureAndroid Platform Architecture
Android Platform Architecture
 
Android architecture
Android architectureAndroid architecture
Android architecture
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Introduction to Android, Architecture & Components
Introduction to  Android, Architecture & ComponentsIntroduction to  Android, Architecture & Components
Introduction to Android, Architecture & Components
 
Android ppt
Android ppt Android ppt
Android ppt
 
Android OS Presentation
Android OS PresentationAndroid OS Presentation
Android OS Presentation
 
My presentation on Android in my college
My presentation on Android in my collegeMy presentation on Android in my college
My presentation on Android in my college
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating system
 
使用 RxJava 让数据流动 (Let data streaming using rxjava)
使用  RxJava 让数据流动 (Let data streaming using rxjava)使用  RxJava 让数据流动 (Let data streaming using rxjava)
使用 RxJava 让数据流动 (Let data streaming using rxjava)
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Cival war 2014
Cival war 2014Cival war 2014
Cival war 2014
 
Buried Treasures
Buried TreasuresBuried Treasures
Buried Treasures
 
lisa.graham.rocks
lisa.graham.rockslisa.graham.rocks
lisa.graham.rocks
 
Ops jaws meetup#3
Ops jaws meetup#3Ops jaws meetup#3
Ops jaws meetup#3
 
Waste aid presentation zero waste conference
 Waste aid presentation zero waste conference Waste aid presentation zero waste conference
Waste aid presentation zero waste conference
 
Sample
SampleSample
Sample
 

Similar to Android architecture

iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
Hussain Behestee
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
Utkarsh Mankad
 

Similar to Android architecture (20)

Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Hilt Annotations
Hilt AnnotationsHilt Annotations
Hilt Annotations
 
Dagger 2 ppt
Dagger 2 pptDagger 2 ppt
Dagger 2 ppt
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
Modern android development
Modern android developmentModern android development
Modern android development
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for Beginners
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Angular Seminar-js
Angular Seminar-jsAngular Seminar-js
Angular Seminar-js
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 

Recently uploaded

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Android architecture

  • 1. Android Architecture Presentation by: Bui Trong An Trip Application Email: trongan93@gmail.com Skype: trongan93 Reference: Technical Uber http://t.uber.com Google Dagger2 - https://google.github.io/dagger Dependency Injection
  • 2. Audience Prerequisites You know how to write a basic Android App Nice to have: You’re familiar with ButterKnife You’ve written a fairly large or growing Andorid App You’ve configured and used networking stacks, imaging libraries, persistent data...
  • 3. Wikipedia Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles.
  • 4. Goal of this presentation To explain the reasons and concepts behind Dependency Injection, specifically Dagger 2 in in the context of Android. To understand the big picture so you’ll know where to look for the answers.
  • 5. TL;DR Separation of Configuration & Usage Maintainability, testability, mockability, low coupling, easy singletons, less boilerplate*
  • 6. Configuration vs Usage SharedPreferences Image Loader (Picasso) Network Client (OkHttp) API Interface (Retrofit) Http Disk Cache Image Disk Cache SessionManager (Auth tokens) Activities Fragments Views Objects
  • 7. Extremely brief history of Dagger Dagger 1 - Square Object Graph Code Generation Some Reflection Dagger 2 - Google Components Code Generation No Reflection
  • 9. TextView mTitleText; TextView mBodyText; TextView mIconText; // in constructor mTitleText = (TextView) findViewById(R.id.title) mBodyText = (TextView) findViewById(R.id.body) mFooterText = (ImageView) findViewById(R.id.icon) Butterknife Analogy @InjectView(R.id.title) TextView mTitleText; @InjectView(R.id.body) TextView mBodyText; @InjectView(R.id.icon) ImageView mIcon; // in constructor Butterknife.inject(this, viewGroup)
  • 10. TextView mTitleText; TextView mBodyText; TextView mIconText; // in constructor mTitleText = (TextView) findViewById(R.id.title) mBodyText = (TextView) findViewById(R.id.body) mFooterText = (ImageView) findViewById(R.id.icon) Butterknife Analogy @InjectView(R.id.title) TextView mTitleText; @InjectView(R.id.body) TextView mBodyText; @InjectView(R.id.icon) ImageView mIcon; // in constructor Butterknife.inject(this, viewGroup) Take all fields with annotation, look in the ViewGroup and find the view by id, cast to expected type, set field.
  • 11. Butterknife Analogy ViewGroup Object findViewById @InjectView Take all fields with annotation, look in the ViewGroup and find the view by id, cast to expected type, set field.
  • 12. Configuration vs Usage SharedPreferences Image Loader (Picasso) Network Client (OkHttp) API Interface (Retrofit) Http Disk Cache Image Disk Cache SessionManager (Auth tokens) Activities Fragments Views Objects @Inject
  • 13. Dagger Usage Component Object “find object by type” @Inject Take all fields with annotation, look in the Component and find the object by type (or create it), and set the field. FKA ObjectGraph
  • 14. Dagger Usage @Inject Picasso mPicasso; @Inject SessionManager mSessionManager; @Inject Toolbar mToolbar; @Inject UberApi mUberApi; // in onCreate() getComponent().inject(this); Take all fields with annotation, look in the Component and find the object by type (or create it), and set the field.
  • 15. Where do we get the Component? public class MyApp extends Application { private MyAppComponent component; @Override public void onCreate() { component = ??? } public MyAppComponent getComponent() { return component; } } <application android:name=".MyApp" …> <activity … /> </application> AndroidManifest.xml MyApp.java
  • 16. public MyComponent getComponent() { return component; } Where do we get the Component? MyApp.java ((MyApp) this.getApplicationContext()).getComponent().inject(this); MyActivity.java
  • 17. MyApp.get(this).getComponent().inject(this); MyActivity.java public static MyApp get(Context context) { return ((MyApp) context.getApplicationContext()); } public MyComponent getComponent() { return component; } Where do we get the Component? MyApp.java
  • 18. public static MyComponent getComponent(Context context) { return ((MyApp) context.getApplicationContext()).component; } Where do we get the Component? MyApp.java MyApp.getComponent(this).inject(this); MyActivity.java
  • 19. public static MyComponent getComponent(Context context) { return ((MyApp) context.getApplicationContext()).component; } Where do we get the Component? MyApp.java MyApp.getComponent(this).inject(this); MyActivity.java MyApp.getComponent(getActivity()).inject(this); MyFragment.java
  • 21. Configuration vsUsage SharedPreferences Image Loader (Picasso/Universal) Network Client (OkHttp) API Interface (Retrofit) Http Disk Cache Image Disk Cache SessionManager (Auth tokens) Activities Fragments Views Objects
  • 22. Modules & Components Activities Fragments Views Objects Networking Module Storage Module Application Module Application Component .inject() FKA ObjectGraph “the graph” Network Client API Interface Disk Cache SharedPreferences Application
  • 23. .inject() .inject() Modules & More Components Activities Fragments Views Objects Networking Module Storage Module Application Module Application Component Activity Module Activity Component Activities Fragments Views Objects FKA ObjectGraph FKA “sub-graph” Toolbar Shared State
  • 24. Defining a Component @Component public interface MyAppComponent { void inject(MyActivity myActivity); } MyAppComponent.java Actual Implementation is generated by Dagger 2. Just an interface:
  • 25. Depending on a Module @Component( modules = { MyAppModule.class, } ) public interface MyAppComponent { void inject(MyActivity myActivity); } MyAppComponent.java
  • 26. Defining a Module @Module public class MyAppModule { private final MyApp app; public MyAppModule(MyApp app) { this.app = app; } @Provides MyApp provideMyApp() { return app; } } MyAppModule.java
  • 27. Defining a Module @Module public class MyAppModule { private final MyApp app; public MyAppModule(MyApp app) { this.app = app; } @Provides @Singleton MyApp provideMyApp() { return app; } } MyAppModule.java
  • 28. Defining a Module @Module public class MyAppModule { private final MyApp app; public MyAppModule(MyApp app) { this.app = app; } @Provides @PerApp MyApp provideMyApp() { return app; } } MyAppModule.java
  • 29. Providing Objects @Module public class ApiModule { @Provides @Singleton RestAdapter provideRestAdapter(Endpoint endpoint, Client client, Converter converter, ApiHeaders headers) { return new RestAdapter.Builder() .setClient(client) .setEndpoint(endpoint) .setConverter(converter) .setRequestInterceptor(headers) .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE) .build(); } } MyAppModule.java
  • 30. Bringing it all together public class MyApp extends Application { private MyComponent component; @Override public void onCreate() { component = ??? } public MyComponent getComponent() { … } } MyApp.java
  • 31. Bringing it all together public class MyApp extends Application { private MyComponent component; @Override public void onCreate() { component = DaggerMyAppComponent.builder() .myAppModule(new MyAppModule(this)) .build(); } public MyComponent getComponent() { … } } MyApp.java
  • 32. The Component Builder @Singleton @Component( modules = MyAppModule.class ) public interface MyAppComponent { void inject(MyApp myApp); } DaggerMyAppComponent.builder() .myAppModule(new MyAppModule(this)) .build(); MyAppComponent.java MyApp.java
  • 33. The Component Builder @Singleton @Component( modules = { MyAppModule.class DataModule.class, NetworkModule.class } ) public interface MyAppComponent { void inject(MyApp myApp); } DaggerMyAppComponent.builder() .myAppModule(new MyAppModule(this)) .dataModule(new DataModule()) .networkModule(new NetworkModule()) .build(); MyAppComponent.java MyApp.java
  • 34. Modules & Components Activities Fragments Views Objects Networking Module Storage Module Application Module Application Component .inject() FKA ObjectGraph “the graph” Network Client API Interface Disk Cache SharedPreferences Application
  • 36. Component Dependencies @Component( dependencies = MyAppComponent.class, modules = MyActivityModule.class ) public interface MyActivityComponent { void inject(MyActivity myActivity); } DaggerMyAppComponent.builder() .myAppComponent( MyApp.getComponent(this)) .myActivityModule( new MyActivityModule(this)) .build(); MyActivityComponent.java MyActivity.java
  • 37. @Component( dependencies = MyAppComponent.class, modules = MyActivityModule.class ) public interface MyActivityComponent { void inject(MyActivity myActivity); void inject(MyFragment myFragment); } Component Dependencies DaggerMyActivityComponent.builder() .myAppComponent(MyApp.getComponent(this)) .myActivityModule(new MyActivityModule(this)) .build(); MyActivityComponent.java MyActivity.java @Component( modules = { MyAppModule.class } ) public interface MyAppComponent { void inject(MyApp myApp); void inject(MyActivity myActivity); MyApp myApp(); SharedPreferences sharedPrefs(); } MyAppComponent.java
  • 38. Scopes @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerApp { } PerApp.java @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity { } PerActivity.java
  • 39. Scopes @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerApp { } PerApp.java @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity { } PerActivity.java @PerApp @Component(…) public interface MyAppComponent { @PerApp @Provides SharedPrefs… @PerActivity @Component(…) public interface MyAactivityComponent { @PerActivity @Provides Toolbar…
  • 40. Constructor Injection @Provides MyThing provideMyThing( SharedPreferences sp, Context context) { return new MyThing(sp, context); } @PerApp class MyThing { private final SharedPRefs… private final Context ... @Inject public MyThing( SharedPreferences sp, Context context) { } }
  • 41. Q & A

Editor's Notes

  1. Just @Inject and don’t think about it. Does Picasso depends on Okhttp and a disk cache? I don’t care. Does SessionManager depend on SharedPrefs or a CookieStore? I don’t care. Does Toolbar need inflating? Doesn’t matter. Does UberApi depend on Okhttp? Or a disk cache? Is logging enabled in debug builds? I don’t worry about that here.
  2. This is a lot of boilerplate in the activity (and every activity), let’s try to move it into the Application
  3. We can create a static getter method for the App
  4. But we don’t really care about the app, we want the component, so let’s just get that. This can be repeated for Activities and other objects if you’d like.
  5. But we don’t really care about the app, we want the component, so let’s just get that. This can be repeated for Activities and other objects if you’d like.
  6. Activity Components can have activity specific objects like Toolbars, Shared UI, etc. Things you would want to inject into Fragments, Views, etc. that you want to only live within the Activity lifecycle.
  7. Define the classes you want to inject
  8. Other thing you want to do is define modules
  9. DaggerMyAppComponent.builder() is generated by dagger.
  10. DaggerMyAppComponent.builder() is generated by dagger.