SlideShare a Scribd company logo
Modern Android app library stack
Tomáš Kypta
#MobCon
Getting into Android
Q: “How do I get the data from the server?”
A: “Use AsyncTask!”
The old school approach™
public class MainActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View view) {
new DownloadTask().execute(inputString);
}
});
}
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override protected String doInBackground(String... params) {
// download some data
}
@Override protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.text);
txt.setText(result);
}
}
}
Old school Android apps
• business logic in activities
• with all the bad stuff such as networking
• and memory leaks
• and crashes
Modern Android apps
• use cleaner architectures
• MVP, MVVM, MVI
• use libraries heavily
• use tests
Libraries
• save time and work
• simplify API
• back-port new APIs to older Android version
Ideal Android Library
• “perform one task and perform it well”
• easy to use
• open-source
• easily available
• through a remote Maven repository
Ideal Android Library
• doesn’t eat too much resources
• doesn’t require too many permissions
• behave nicely when crashing
“I wan’t my app to work on Android from version 4.1.”
98% of Android devices!
Support libraries
• available through Android SDK
• backport newer Android APIs
• helper classes
• debugging, testing, utilities
Support libraries
• AsyncTaskLoader
• com.android.support:support-core-utils:25.3.0
• ViewPager
• com.android.support:support-core-ui:25.3.0
• support fragments
• com.android.support:support-fragment:25.3.0
Support libraries
• AppCompatActivity, ActionBar
• com.android.support:appcompat-v7:25.3.0
• RecyclerView
• com.android.support:recyclerview-v7:25.3.0
• CardView
• com.android.support:cardview-v7:25.3.0
Support libraries
• com.android.support:support-annotations:25.3.0
• useful annotations
• StringRes, IntDef, Nullable, UiThread, WorkerThread, CallSuper,
VisibleForTesting, …
• com.android.support:design:25.3.0
• Material design
Support libraries
• Having more than 64k methods?
• And supporting Android prior 5.0?
• com.android.support:multidex:1.0.1
“This dependency injection thing sounds useful.”
Dagger 2
• dependency injection framework for Android and Java
• avoids reflection
• uses compile-time generated code
Dagger 2
public class SimpleGameProvider {
private ApiProvider mApiProvider;
private StorageProvider mStorageProvider;
@Inject
public SimpleProvider(ApiProvider apiProvider, StorageProvider storageProvider) {
mApiProvider = apiProvider;
mStorageProvider = storageProvider;
}
public void doSomething() {
// …
}
}
Dagger 2
@Module
public class AppModule {
private Context mApplicationContext;
public AppModule(Context applicationContext) {
mApplicationContext = applicationContext;
}
@Singleton @Provides
protected OtherProvider provideTheOther(Context context) {
return new OtherProvider(context);
}
}
Dagger 2
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity activity);
}
Dagger 2
public class MainActivity extends AppCompatActivity {
@Inject SimpleProvider mSimpleProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication) getApplication()).getAppComponent().inject(this);
// and now we can use mSimpleProvider
}
}
“My server has this REST API…”
Retrofit
• simple REST client for Android and Java
• annotation-based API
• type-safe
• Rx compatible
Retrofit
public interface GitHubApi {
@GET("/users/{username}")
User getUser(@Path("username") String username);
@GET("/users/{username}/repos")
List<Repo> getUserRepos(@Path("username") String username);
@POST("/orgs/{org}/repos")
RepoCreationResponse createRepoInOrganization(
@Path("org") String organization,
@Body RepoCreationRequest request);
}
Retrofit
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(GITHUB_API_URL)
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/vnd.github.v3+json");
}
})
.setLogLevel(RestAdapter.LogLevel.BASIC)
.build();
GitHubApi gitHubApi = adapter.create(GitHubApi.class);
“And my server has this fancy new features…”
OkHttp
• an efficient HTTP client for Android and Java
• requests can be easily customized
• support for HTTP/2
• connection pooling
• transparent GZIP
• response caching
OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
OkHttp
• Works out of the box with the latest Retrofit!
“The server returns 400. What’s wrong?”
Stetho
• A debug bridge
• hooks into Chrome Developer Tools
Stetho
• network inspection
• database inspection
• view hierarchy
• dumpapp system allowing custom plugins
• command-line interface for communication with the plugins
Stetho
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
Stetho
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
“Why I’m getting this OutOfMemoryError?”
LeakCanary
• memory leak detection library
• notifies about memory leaks during app development
LeakCanary
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}
“How to display this remote product image?”
Image loaders
• tons of libs
• Universal Image Loader
• Picasso
• Glide
Picasso
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(vImageView);
“How can I notify that class?“
“There has to be some way without refactoring the whole
thing!”
Event bus
• for communication between decoupled parts of an app
• EventBus
EventBus
• events
• subscribers
• register and unregister
• post events
public static class MessageEvent { /* fields if needed */ }
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* handle event */};
EventBus.getDefault().register(this);
EventBus.getDefault().unregister(this);
EventBus.getDefault().post(new MessageEvent());
“How do I get the data from the server?”
“And I have to combine couple of sources.”
RxJava
• general Java library
• reactive programming
• push concept
• composable data flow
RxJava
• useful for simple async processing
• async composition
• offers simple chaining of operations on data
• eliminates callback hell
RxJava
• works well with Retrofit
• can completely replace event bus libraries
• hard to learn
• RxJava 1 vs. RxJava 2
• they will coexist for some time
RxJava data flow
Observable
.from(new String[]{"Hello", "Droidcon!"}) creation
RxJava data flow
Observable
.from(new String[]{"Hello", "Droidcon!"})
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s.toUpperCase(Locale.getDefault());
}
})
creation
RxJava data flow
Observable
.from(new String[]{"Hello", "Droidcon!"})
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s.toUpperCase(Locale.getDefault());
}
})
.reduce(new Func2<String, String, String>() {
@Override
public String call(String s, String s2) {
return s + ' ' + s2;
}
})
creation
transformation
RxJava data flow
Observable
.from(new String[]{"Hello", "Droidcon!"})
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s.toUpperCase(Locale.getDefault());
}
})
.reduce(new Func2<String, String, String>() {
@Override
public String call(String s, String s2) {
return s + ' ' + s2;
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Timber.i(s);
}
});
creation
transformation
subscription
RxJava data flow with Java 8
creation
transformation
subscription
Observable
.from(new String[]{"Hello", "Droidcon!"})
.map(s -> s.toUpperCase(Locale.getDefault()))
.reduce((s,s2) -> s + ' ' + s2)
.subscribe(s -> Timber.i(s));
Other Rx libraries
RxAndroid
RxBinding
RxLifecycle
RxNavi
SQLBrite
RxRelay
“This new feature is great! I bet users will love it!”
Analytics & crash reporting
• Google Analytics
• Crashlytics
• Firebase
“I don’t like this Java language.”
Kotlin
• not a library
• a JVM programming language
• “Swift for Android devs"
Q: “So all I have to do is to Google for a library to do the thing?”
A: “think wisely before adding a new library.”
Final thoughts
• many potential problems
• transitive dependencies
• permissions
• app size
• slow app start
• threads
• logs
Questions?

More Related Content

What's hot

Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip Ozturk
ZeroTurnaround
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IO
ondraz
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Michaël Figuière
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 

What's hot (19)

Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 
New text document
New text documentNew text document
New text document
 
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip Ozturk
 
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
mDevCamp - The Best from Google IO
mDevCamp - The Best from Google IOmDevCamp - The Best from Google IO
mDevCamp - The Best from Google IO
 
Ejemplo radio
Ejemplo radioEjemplo radio
Ejemplo radio
 
Multi-threaded CoreData Done Right
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Right
 
Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]
 
EPAM IT WEEK: AEM & TDD. It's so boring...
EPAM IT WEEK: AEM & TDD. It's so boring...EPAM IT WEEK: AEM & TDD. It's so boring...
EPAM IT WEEK: AEM & TDD. It's so boring...
 
JavaEE 8 on a diet with Payara Micro 5
JavaEE 8 on a diet with Payara Micro 5JavaEE 8 on a diet with Payara Micro 5
JavaEE 8 on a diet with Payara Micro 5
 
Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!Cassandra summit 2013 - DataStax Java Driver Unleashed!
Cassandra summit 2013 - DataStax Java Driver Unleashed!
 
Advanced Akka For Architects
Advanced Akka For ArchitectsAdvanced Akka For Architects
Advanced Akka For Architects
 
Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]
 
Dagger 2 - Injeção de Dependência
Dagger 2 - Injeção de DependênciaDagger 2 - Injeção de Dependência
Dagger 2 - Injeção de Dependência
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Processing large-scale graphs with Google(TM) Pregel
Processing large-scale graphs with Google(TM) PregelProcessing large-scale graphs with Google(TM) Pregel
Processing large-scale graphs with Google(TM) Pregel
 

Viewers also liked

Thinkoutofthebox eng-090317095329-phpapp01 ca
Thinkoutofthebox eng-090317095329-phpapp01 caThinkoutofthebox eng-090317095329-phpapp01 ca
Thinkoutofthebox eng-090317095329-phpapp01 ca
Carol Aw
 
Le programme de recherche et de développement de l'Ifsttar 2017
Le programme de recherche et de développement de l'Ifsttar 2017Le programme de recherche et de développement de l'Ifsttar 2017

Viewers also liked (18)

34classification (part 2)
34classification (part 2)34classification (part 2)
34classification (part 2)
 
معايير الجودة في التعليم الالكتروني- د. خالد بكرو Quality Standards in e...
معايير الجودة في التعليم الالكتروني- د. خالد بكرو  Quality   Standards in   e...معايير الجودة في التعليم الالكتروني- د. خالد بكرو  Quality   Standards in   e...
معايير الجودة في التعليم الالكتروني- د. خالد بكرو Quality Standards in e...
 
danh mục thành phần các loại hợp kim nhôm
danh mục thành phần các loại hợp kim nhômdanh mục thành phần các loại hợp kim nhôm
danh mục thành phần các loại hợp kim nhôm
 
Thinkoutofthebox eng-090317095329-phpapp01 ca
Thinkoutofthebox eng-090317095329-phpapp01 caThinkoutofthebox eng-090317095329-phpapp01 ca
Thinkoutofthebox eng-090317095329-phpapp01 ca
 
Steps In Experimental Design ( QE )
Steps In Experimental Design ( QE )Steps In Experimental Design ( QE )
Steps In Experimental Design ( QE )
 
The last of the Μohicans,Κ.Μελά-Ειρ.Πέτο-Αγ.Μπουντούρη
The last of the Μohicans,Κ.Μελά-Ειρ.Πέτο-Αγ.ΜπουντούρηThe last of the Μohicans,Κ.Μελά-Ειρ.Πέτο-Αγ.Μπουντούρη
The last of the Μohicans,Κ.Μελά-Ειρ.Πέτο-Αγ.Μπουντούρη
 
A Presentation on Railway Passenger Reservation System (PRS) by Sourabh Kumar
A Presentation on Railway Passenger Reservation System (PRS) by Sourabh KumarA Presentation on Railway Passenger Reservation System (PRS) by Sourabh Kumar
A Presentation on Railway Passenger Reservation System (PRS) by Sourabh Kumar
 
New york
New yorkNew york
New york
 
EU Statement, Rome 25.03
EU Statement, Rome 25.03EU Statement, Rome 25.03
EU Statement, Rome 25.03
 
ハロとAi
ハロとAiハロとAi
ハロとAi
 
Live to Add Value to Other People
Live to Add Value to Other PeopleLive to Add Value to Other People
Live to Add Value to Other People
 
L'avortement tardif et les infanticides néonataux en europe, eclj, 26 juin 2015
L'avortement tardif et les infanticides néonataux en europe, eclj, 26 juin 2015L'avortement tardif et les infanticides néonataux en europe, eclj, 26 juin 2015
L'avortement tardif et les infanticides néonataux en europe, eclj, 26 juin 2015
 
Mega trends tanyer sonmezer MCT
Mega trends tanyer sonmezer MCTMega trends tanyer sonmezer MCT
Mega trends tanyer sonmezer MCT
 
中国貿易統計
中国貿易統計中国貿易統計
中国貿易統計
 
Suministro de energía eléctrica para Usuarios Calificados en México
Suministro de energía eléctrica para Usuarios Calificados en MéxicoSuministro de energía eléctrica para Usuarios Calificados en México
Suministro de energía eléctrica para Usuarios Calificados en México
 
QR Code pour des pratiques de lecture autonomes ExplorCamp ludovia2013
QR Code pour des pratiques de lecture autonomes ExplorCamp ludovia2013QR Code pour des pratiques de lecture autonomes ExplorCamp ludovia2013
QR Code pour des pratiques de lecture autonomes ExplorCamp ludovia2013
 
Le programme de recherche et de développement de l'Ifsttar 2017
Le programme de recherche et de développement de l'Ifsttar 2017Le programme de recherche et de développement de l'Ifsttar 2017
Le programme de recherche et de développement de l'Ifsttar 2017
 
Impact of 2015 Amendments to Arbitration & Conciliation Act
Impact of 2015 Amendments to Arbitration & Conciliation Act Impact of 2015 Amendments to Arbitration & Conciliation Act
Impact of 2015 Amendments to Arbitration & Conciliation Act
 

Similar to Modern Android app library stack

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126
Go Tanaka
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
Droidcon Berlin
 

Similar to Modern Android app library stack (20)

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
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 

More from Tomáš Kypta

Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012
Tomáš Kypta
 

More from Tomáš Kypta (20)

Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Android Develpment vol. 3, MFF UK, 2015
Android Develpment vol. 3, MFF UK, 2015Android Develpment vol. 3, MFF UK, 2015
Android Develpment vol. 3, MFF UK, 2015
 
Writing testable Android apps
Writing testable Android appsWriting testable Android apps
Writing testable Android apps
 
Android Develpment vol. 2, MFF UK, 2015
Android Develpment vol. 2, MFF UK, 2015Android Develpment vol. 2, MFF UK, 2015
Android Develpment vol. 2, MFF UK, 2015
 
ProGuard
ProGuardProGuard
ProGuard
 
Unit testing and Android
Unit testing and AndroidUnit testing and Android
Unit testing and Android
 
Android Development for Phone and Tablet
Android Development for Phone and TabletAndroid Development for Phone and Tablet
Android Development for Phone and Tablet
 
Android development - the basics, MFF UK, 2014
Android development - the basics, MFF UK, 2014Android development - the basics, MFF UK, 2014
Android development - the basics, MFF UK, 2014
 
Android Libraries
Android LibrariesAndroid Libraries
Android Libraries
 
Android Development 201
Android Development 201Android Development 201
Android Development 201
 
Android development - the basics, MFF UK, 2013
Android development - the basics, MFF UK, 2013Android development - the basics, MFF UK, 2013
Android development - the basics, MFF UK, 2013
 
Užitečné Android knihovny pro vývoj a testování
Užitečné Android knihovny pro vývoj a testováníUžitečné Android knihovny pro vývoj a testování
Užitečné Android knihovny pro vývoj a testování
 
Programování pro Android - úvod, FI MUNI, 2013
Programování pro Android - úvod, FI MUNI, 2013Programování pro Android - úvod, FI MUNI, 2013
Programování pro Android - úvod, FI MUNI, 2013
 
Stylování ActionBaru
Stylování ActionBaruStylování ActionBaru
Stylování ActionBaru
 
Android development - the basics, MFF UK, 2012
Android development - the basics, MFF UK, 2012Android development - the basics, MFF UK, 2012
Android development - the basics, MFF UK, 2012
 
Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 

Modern Android app library stack

  • 1. Modern Android app library stack Tomáš Kypta #MobCon
  • 3. Q: “How do I get the data from the server?”
  • 4. A: “Use AsyncTask!” The old school approach™
  • 5. public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener { public void onClick(View view) { new DownloadTask().execute(inputString); } }); } private class DownloadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { // download some data } @Override protected void onPostExecute(String result) { TextView txt = (TextView) findViewById(R.id.text); txt.setText(result); } } }
  • 6. Old school Android apps • business logic in activities • with all the bad stuff such as networking • and memory leaks • and crashes
  • 7. Modern Android apps • use cleaner architectures • MVP, MVVM, MVI • use libraries heavily • use tests
  • 8. Libraries • save time and work • simplify API • back-port new APIs to older Android version
  • 9. Ideal Android Library • “perform one task and perform it well” • easy to use • open-source • easily available • through a remote Maven repository
  • 10. Ideal Android Library • doesn’t eat too much resources • doesn’t require too many permissions • behave nicely when crashing
  • 11. “I wan’t my app to work on Android from version 4.1.” 98% of Android devices!
  • 12. Support libraries • available through Android SDK • backport newer Android APIs • helper classes • debugging, testing, utilities
  • 13. Support libraries • AsyncTaskLoader • com.android.support:support-core-utils:25.3.0 • ViewPager • com.android.support:support-core-ui:25.3.0 • support fragments • com.android.support:support-fragment:25.3.0
  • 14. Support libraries • AppCompatActivity, ActionBar • com.android.support:appcompat-v7:25.3.0 • RecyclerView • com.android.support:recyclerview-v7:25.3.0 • CardView • com.android.support:cardview-v7:25.3.0
  • 15. Support libraries • com.android.support:support-annotations:25.3.0 • useful annotations • StringRes, IntDef, Nullable, UiThread, WorkerThread, CallSuper, VisibleForTesting, … • com.android.support:design:25.3.0 • Material design
  • 16. Support libraries • Having more than 64k methods? • And supporting Android prior 5.0? • com.android.support:multidex:1.0.1
  • 17. “This dependency injection thing sounds useful.”
  • 18. Dagger 2 • dependency injection framework for Android and Java • avoids reflection • uses compile-time generated code
  • 19. Dagger 2 public class SimpleGameProvider { private ApiProvider mApiProvider; private StorageProvider mStorageProvider; @Inject public SimpleProvider(ApiProvider apiProvider, StorageProvider storageProvider) { mApiProvider = apiProvider; mStorageProvider = storageProvider; } public void doSomething() { // … } }
  • 20. Dagger 2 @Module public class AppModule { private Context mApplicationContext; public AppModule(Context applicationContext) { mApplicationContext = applicationContext; } @Singleton @Provides protected OtherProvider provideTheOther(Context context) { return new OtherProvider(context); } }
  • 21. Dagger 2 @Singleton @Component(modules = {AppModule.class}) public interface AppComponent { void inject(MainActivity activity); }
  • 22. Dagger 2 public class MainActivity extends AppCompatActivity { @Inject SimpleProvider mSimpleProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((MyApplication) getApplication()).getAppComponent().inject(this); // and now we can use mSimpleProvider } }
  • 23. “My server has this REST API…”
  • 24. Retrofit • simple REST client for Android and Java • annotation-based API • type-safe • Rx compatible
  • 25. Retrofit public interface GitHubApi { @GET("/users/{username}") User getUser(@Path("username") String username); @GET("/users/{username}/repos") List<Repo> getUserRepos(@Path("username") String username); @POST("/orgs/{org}/repos") RepoCreationResponse createRepoInOrganization( @Path("org") String organization, @Body RepoCreationRequest request); }
  • 26. Retrofit RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(GITHUB_API_URL) .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("Accept", "application/vnd.github.v3+json"); } }) .setLogLevel(RestAdapter.LogLevel.BASIC) .build(); GitHubApi gitHubApi = adapter.create(GitHubApi.class);
  • 27. “And my server has this fancy new features…”
  • 28. OkHttp • an efficient HTTP client for Android and Java • requests can be easily customized • support for HTTP/2 • connection pooling • transparent GZIP • response caching
  • 29. OkHttp OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string();
  • 30. OkHttp • Works out of the box with the latest Retrofit!
  • 31. “The server returns 400. What’s wrong?”
  • 32. Stetho • A debug bridge • hooks into Chrome Developer Tools
  • 33. Stetho • network inspection • database inspection • view hierarchy • dumpapp system allowing custom plugins • command-line interface for communication with the plugins
  • 34.
  • 35. Stetho public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Stetho.initializeWithDefaults(this); } }
  • 36.
  • 37. Stetho OkHttpClient okHttpClient = new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .build();
  • 38. “Why I’m getting this OutOfMemoryError?”
  • 39. LeakCanary • memory leak detection library • notifies about memory leaks during app development
  • 40. LeakCanary dependencies { debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' }
  • 41. “How to display this remote product image?”
  • 42. Image loaders • tons of libs • Universal Image Loader • Picasso • Glide
  • 44. “How can I notify that class?“ “There has to be some way without refactoring the whole thing!”
  • 45. Event bus • for communication between decoupled parts of an app • EventBus
  • 46. EventBus • events • subscribers • register and unregister • post events public static class MessageEvent { /* fields if needed */ } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) {/* handle event */}; EventBus.getDefault().register(this); EventBus.getDefault().unregister(this); EventBus.getDefault().post(new MessageEvent());
  • 47. “How do I get the data from the server?” “And I have to combine couple of sources.”
  • 48. RxJava • general Java library • reactive programming • push concept • composable data flow
  • 49. RxJava • useful for simple async processing • async composition • offers simple chaining of operations on data • eliminates callback hell
  • 50. RxJava • works well with Retrofit • can completely replace event bus libraries • hard to learn • RxJava 1 vs. RxJava 2 • they will coexist for some time
  • 51. RxJava data flow Observable .from(new String[]{"Hello", "Droidcon!"}) creation
  • 52. RxJava data flow Observable .from(new String[]{"Hello", "Droidcon!"}) .map(new Func1<String, String>() { @Override public String call(String s) { return s.toUpperCase(Locale.getDefault()); } }) creation
  • 53. RxJava data flow Observable .from(new String[]{"Hello", "Droidcon!"}) .map(new Func1<String, String>() { @Override public String call(String s) { return s.toUpperCase(Locale.getDefault()); } }) .reduce(new Func2<String, String, String>() { @Override public String call(String s, String s2) { return s + ' ' + s2; } }) creation transformation
  • 54. RxJava data flow Observable .from(new String[]{"Hello", "Droidcon!"}) .map(new Func1<String, String>() { @Override public String call(String s) { return s.toUpperCase(Locale.getDefault()); } }) .reduce(new Func2<String, String, String>() { @Override public String call(String s, String s2) { return s + ' ' + s2; } }) .subscribe(new Action1<String>() { @Override public void call(String s) { Timber.i(s); } }); creation transformation subscription
  • 55. RxJava data flow with Java 8 creation transformation subscription Observable .from(new String[]{"Hello", "Droidcon!"}) .map(s -> s.toUpperCase(Locale.getDefault())) .reduce((s,s2) -> s + ' ' + s2) .subscribe(s -> Timber.i(s));
  • 57. “This new feature is great! I bet users will love it!”
  • 58. Analytics & crash reporting • Google Analytics • Crashlytics • Firebase
  • 59. “I don’t like this Java language.”
  • 60. Kotlin • not a library • a JVM programming language • “Swift for Android devs"
  • 61. Q: “So all I have to do is to Google for a library to do the thing?”
  • 62. A: “think wisely before adding a new library.”
  • 63. Final thoughts • many potential problems • transitive dependencies • permissions • app size • slow app start • threads • logs