SlideShare a Scribd company logo
Think About Async
Think Async
Understanding the Complexity of Multi-Threading
Who Are We?
Avi Kabizon @avikabizon
R&D Team Manager
AppPulse Mobile R&D
avi.kabizon@hpe.com
Amichai Nitsan @aminits
Senior Architect
AppPulse Suite R&D
amichai.nitsan@hpe.com
. . . Our Day Job . . .
–User Experience Monitoring:
Performance
Stability
Usage
Resource utilization
–Tag-less and codeless
–SaaS based, Free trial
3
saas.hpe.com/en-us/software/AppPulse-mobile
4
Motivation
Async Patterns in Android
Real World Examples
Summary
Agenda
Motivation
Concurrency And Android Programming
5
6
Why Waiting
Is Torture
Alex Stone AUG. 18, 2012
http://www.nytimes.com/2012/08/19/opinion/sunday/why-waiting-in-line-is-torture.html
Why Concurrency?
7
It is all about the User Experience
Processing
of data
Waiting for
server
Housekeeping
Android and Concurrency
Pretty sure you all know but…
– The UI thread is not allowed to access the network (a crash in StrictMode)
… But also other long tasks are not allowed
– Avoid the dreadful “Application Not Responding” (ANR) dialog:
– Respond to a user action whithin 5 seconds
– Finish executing a BroadcastReceiver within 10 seconds
8
Android Application Responsiveness
– An application should respond to any user action within 100 - 200 ms
– “response” ≠ work is done
– Indicate that “work is being done, and there is progress”  but entertain the
users while they wait
Make sure every user action is handled as fast as possible
Users appreciate if you “take notes” and continue to serve them
– Think Async:
– Do users really need to wait for this image to upload?
– Can the users start working with partial data?
– Is the screen rendering waiting for unrelated actions?
9
Thread Performance Isolation
10
– How are threads behaving?
– Challenges with existing tools:
– Debugger
– Logs (System.err.println)
– Traceview:
– Capture button
– Code tagging (android.os.Debug.startMethodTracing)
Async Patterns In Android
#PERFMATTERS
@YouTube
11
AsyncTask
– Easy to use
– Short tasks that update the UI
– Tied to fragment or activity lifecycle
– Android executes AsyncTask tasks
serially by default
12
class AsyncTask
// init UI
onPreExecute()
// start background
doInBackground()
// update UI
onProgressUpdate()
// Update UI
onPostExecute()
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
Loader
13
class CursorLoader
// returns a cursor
public Cursor loadInBackground()
– Loads data from an external
source into a local DB
– Ideal for sync that is
independent of user actions
– Not tied to fragment or activity
– Complex to use in code
HandlerThread
– A background thread for
handling multiple jobs in
the background
– Runs outside of activity
lifecycle
– Long running processes
– Need to manage lifecycle
manually - call quit()
– No built-in mechanism for
reporting back
– Set the right thread
priority!
14
HandlerThread handlerThread = new
HandlerThread("MyHandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);
…
handler.post(new Runnable(){…});
IntentService
– HandlerThread runs as a Service
– Handles incoming Intents on a
separate process
– Best for intents without
foreground updates
– Will block other incoming intents
15
class IntentService
// Do work here
onHandleIntent(Intent workIntent)
<application>
<service android:name=".MyService"
android:exported="false"/>
<application/>
ThreadPoolExecutor
– Manages a pool of worker
threads
– Tasks run in parallel
– Powerful tool for demanding
situations
– Each thread consumes at least
64KB of mem
– Need to find the magical min and
max number of threads
16
ThreadPoolExecutor executor =
new ThreadPoolExecutor();
executor.execute(new Runnable() {
public void run() {
// Do some long running }
});
Java Thread
– Fine control on the details
… but lots of code
– Usually used as last resort
17
new Thread(new Runnable() {
public void run() {
// do background job
}
}).start();
JobScheduler
SyncAdapter
ThinkAsync – The Real World
18
Think Async
19
Method
Network
Sleep/Wait
Scale:
Main
com.kayak.android.car.CarActivity$5.onClick
com.kayak.android.car.CarResultFragment.onCreateV
iew()
com.kayak.android.currency.CurrencyController.lock(
)
[POST]https://www.kayak.com/s/impression/inline
UI finished rendering
Think Network - Real world examples
20
Think Async - Network
Make a network call. No subsequent UI update.
onclick()
Network call
Main
doInbackground()
User action: Submit registration form
Think Async - Network
Make a network call. Process the result and update UI.
com.amazon.mShop.home.HomeView$2.onClick()
com.amazon.rio.j2me.client.util.Worker.run()
[POST] https://msh.amazon.com/mShop/service
com.amazon.mShop.categoryBrowse.CategoryBrowseActivity.onResume()
com.amazon.mShop.MShopActivity.onResume()
com.amazon.mShop.android.AmazonActivity.onResume()
…
com.amazon.mShop.android.AmazonActivity$1.onAnimationStart()
com.amazon.mShop.android.AmazonActivity$1.onAnimationEnd()
…
com.amazon.mShop.categoryBrowse.CategoryBrowseMainPageView$CategoryMainViewAdapter.g
Main
User action: Open Shop by department activity
Think Async - Network
Pattern analysis
User action: Search cars
Think Async - Network
Pattern analysis
onPostExecute() {
…
startAsyncTask(download);
}
User action: Search cars
Think Async - Network
“Stairs” pattern analysis
• Creates new async task during onPostExecute()
• No parallelism of HTTP calls
• Thread creation overhead
26
Think Async - Network
Handler thread
User action: Open main activity
Handler thread
while (callable queue not empty) {
runCallable (queue.poll);
}
27
Think Async - Network
Handler thread
User action: Open main activity
• Single thread performs multiple HTTP calls on same method
• No thread creation overhead
• Easier to make fewer HTTP calls
Think Async - Network
Thread per HTTP call
com.amazon.mShop.android.net.HttpFetcher.run()
[GET] http://ecx.images-amazon.com/images/I/51wxjlaS0qL._SL360_.jpg
Method
Network
Sleep/Wait
Scale:
Main
User action: Browse by category
foreach (resource to download) {
startAsyncTask(resource)
}
Think Async - Network
Thread per HTTP call
Parallelization of HTTP calls
New thread for each HTTP call
30
Think Async - Network
Thread pool
Reused Threads
User action: Open main tab
Think Async - Network
Thread pool
Parallelization of http calls
Efficient reuse of threads
ThinkAsync – UI and Data
32
Think UI
Keep smooth UI by avoiding frame loss
• Most Android devices refresh the screen 60 times a second
• That means your code running on the UI thread has only ~16ms to:
• Measure
• Layout
• Draw
• Keep UI thread only for UI
• Remember that all the on* methods run inside the UI Thread
Think UI
Speed up scrolling
• Use Loaders
• Use libraries, for example Glide or Picasso for image loading
• Use RecyclerView or ListView with view holder pattern to avoid
findViewById() calls
Think UI
Optimize animations
• Avoid layout or inflation during animation
• Watch out for lifecycle events
• Avoid initiating animations in onCreate, onStart or onResume.
• Initiate animations on user events such as onClick and disable touch
events until animation is complete.
• Don't initiate more than 2 animations simultaneously
Think UI
Animations in Think Async
Fade in animation Shrink and grow animation
Fragment.onResum
e()
Shrink and grow
animation
Fade in animation
Layout change
between animations
Without layout change
between animations
Wrap Up
37
Summary
38
Async
Patterns
Real-world
examples
Async
your apps!
Fighting to save the
Digital User Experience
Follow the adventures of the UX-Men:
• AppPulse Active
• AppPulse Mobile
• AppPulse Trace
90%
1/3
saas.hpe.com/en-us/software/AppPulse-mobile
40
Thank You!
Contact us:
amichai.nitsan@hpe.com
avi.kabizon@hpe.com
saas.hpe.com/en-us/software/AppPulse-mobile

More Related Content

PDF
Build an App with Blindfold - Britt Barak
PDF
Engineering Wunderlist for Android - Ceasr Valiente, 6Wunderkinder
PPTX
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
PPTX
EXPERTALKS: Nov 2012 - Web Application Clustering
PPTX
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
PDF
Ajax & Reverse Ajax Presenation
PPTX
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
PDF
Stress Testing and Analysing MapServer Performance
Build an App with Blindfold - Britt Barak
Engineering Wunderlist for Android - Ceasr Valiente, 6Wunderkinder
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
EXPERTALKS: Nov 2012 - Web Application Clustering
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
Ajax & Reverse Ajax Presenation
SenchaCon 2016: Handling Undo-Redo in Sencha Applications - Nickolay Platonov
Stress Testing and Analysing MapServer Performance

What's hot (19)

PPTX
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...
PPT
Android - Thread, Handler and AsyncTask
PDF
Play framework productivity formula
PDF
Servlet and JSP
PPTX
Spring boot for buidling microservices
PDF
Three Lessons about Gatling and Microservices
PPT
Java - Servlet - Mazenet Solution
PDF
Play Framework and Activator
PPTX
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
PDF
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
PDF
Play framework
PPTX
Spring boot Introduction
PPTX
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
PPTX
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
PDF
Securing Microservices using Play and Akka HTTP
PPT
Java Servlet
PPTX
ASP.NET MVC 4 Request Pipeline Internals
PDF
Akka and AngularJS – Reactive Applications in Practice
PPTX
Reverse ajax in 2014
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...
Android - Thread, Handler and AsyncTask
Play framework productivity formula
Servlet and JSP
Spring boot for buidling microservices
Three Lessons about Gatling and Microservices
Java - Servlet - Mazenet Solution
Play Framework and Activator
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
Play framework
Spring boot Introduction
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
Securing Microservices using Play and Akka HTTP
Java Servlet
ASP.NET MVC 4 Request Pipeline Internals
Akka and AngularJS – Reactive Applications in Practice
Reverse ajax in 2014
Ad

Viewers also liked (16)

PDF
Cognitive interaction using Wearables - Eyal herman, IBM
PDF
Mobile App Europe 2015 Pulse UX Workshop Presentation
PDF
Context is Everything - Royi Benyossef
PPTX
Creating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBM
PDF
3 things every Android developer must know about Microsoft - Ido Volff, Micro...
PDF
Android is going to Go! - Android and goland - Almog Baku
PPTX
Good Rules for Bad Apps - Shem magnezi
PDF
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
PDF
Android Application Optimization: Overview and Tools - Oref Barad, AVG
PDF
Mobile SDKs: Use with Caution - Ori Lentzitzky
PPTX
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
PPTX
Set it and forget it: Let the machine learn its job - Guy Baron, Vonage
PDF
Knock knock! Who's there? Doze. - Yonatan Levin
PPTX
Optimize your delivery and quality with the right release methodology and too...
PDF
Intro to Dependency Injection - Or bar
PDF
Android Continuous Integration and Automation - Enrique Lopez Manas, Sixt
Cognitive interaction using Wearables - Eyal herman, IBM
Mobile App Europe 2015 Pulse UX Workshop Presentation
Context is Everything - Royi Benyossef
Creating killer apps powered by watson cognitive services - Ronen Siman-Tov, IBM
3 things every Android developer must know about Microsoft - Ido Volff, Micro...
Android is going to Go! - Android and goland - Almog Baku
Good Rules for Bad Apps - Shem magnezi
Write code that writes code! A beginner's guide to Annotation Processing - Ja...
Android Application Optimization: Overview and Tools - Oref Barad, AVG
Mobile SDKs: Use with Caution - Ori Lentzitzky
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Set it and forget it: Let the machine learn its job - Guy Baron, Vonage
Knock knock! Who's there? Doze. - Yonatan Levin
Optimize your delivery and quality with the right release methodology and too...
Intro to Dependency Injection - Or bar
Android Continuous Integration and Automation - Enrique Lopez Manas, Sixt
Ad

Similar to Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & Amichai Nitzan (20)

PDF
Asynchronous Programming in Android
PDF
Programming Sideways: Asynchronous Techniques for Android
PDF
Get Off My Thread! - keep your UI super-responsive
ODP
Android App Development - 07 Threading
PDF
Internals of AsyncTask
PPTX
Efficient Android Threading
PPTX
Lecture #2 threading, networking &amp; permissions final version #2
PPTX
Android Connecting to internet Part 2
PDF
Android concurrency
PPTX
Android Thread
PPTX
mobile development with androiddfdgdfhdgfdhf.pptx
PDF
Not Quite As Painful Threading
PDF
[Android] Multiple Background Threads
PPTX
Introduction to Android - Session 3
PPT
Tech talk
PDF
Google Developer Day 2010 Japan: 高性能な Android アプリを作るには (ティム ブレイ)
PDF
Android - Background operation
PDF
Android development training programme , Day 3
PPTX
Threads handlers and async task, widgets - day8
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Asynchronous Programming in Android
Programming Sideways: Asynchronous Techniques for Android
Get Off My Thread! - keep your UI super-responsive
Android App Development - 07 Threading
Internals of AsyncTask
Efficient Android Threading
Lecture #2 threading, networking &amp; permissions final version #2
Android Connecting to internet Part 2
Android concurrency
Android Thread
mobile development with androiddfdgdfhdgfdhf.pptx
Not Quite As Painful Threading
[Android] Multiple Background Threads
Introduction to Android - Session 3
Tech talk
Google Developer Day 2010 Japan: 高性能な Android アプリを作るには (ティム ブレイ)
Android - Background operation
Android development training programme , Day 3
Threads handlers and async task, widgets - day8
Thread In Android-Mastering Concurrency for Responsive Apps.pdf

More from DroidConTLV (20)

PDF
Mobile Development in the Information Age - Yossi Elkrief, Nike
PDF
Doing work in the background - Darryn Campbell, Zebra Technologies
PDF
No more video loss - Alex Rivkin, Motorola Solutions
PDF
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
PDF
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
PDF
MVVM In real life - Lea Cohen Tannoudji, Lightricks
PDF
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
PDF
Building Apps with Flutter - Hillel Coren, Invoice Ninja
PDF
New Android Project: The Most Important Decisions - Vasiliy Zukanov
PDF
Designing a Design System - Shai Mishali, Gett
PDF
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
PDF
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
PDF
Flutter State Management - Moti Bartov, Tikal
PDF
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
PDF
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
PDF
DroidconTLV 2019
PDF
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
PDF
Introduction to React Native - Lev Vidrak, Wix
PDF
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
PDF
Educating your app – adding ML edge to your apps - Maoz Tamir
Mobile Development in the Information Age - Yossi Elkrief, Nike
Doing work in the background - Darryn Campbell, Zebra Technologies
No more video loss - Alex Rivkin, Motorola Solutions
Mobile at Scale: from startup to a big company - Dor Samet, Booking.com
LiveData on Steroids - Giora Shevach + Shahar Ben Moshe, Climacell
MVVM In real life - Lea Cohen Tannoudji, Lightricks
Best Practices for Using Mobile SDKs - Lilach Wagner, SafeDK (AppLovin)
Building Apps with Flutter - Hillel Coren, Invoice Ninja
New Android Project: The Most Important Decisions - Vasiliy Zukanov
Designing a Design System - Shai Mishali, Gett
The Mighty Power of the Accessibility Service - Guy Griv, Pepper
Kotlin Multiplatform in Action - Alexandr Pogrebnyak - IceRockDev
Flutter State Management - Moti Bartov, Tikal
Reactive UI in android - Gil Goldzweig Goldbaum, 10bis
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
DroidconTLV 2019
Ok google, it's time to bot! - Hadar Franco, Albert + Stav Levi, Monday
Introduction to React Native - Lev Vidrak, Wix
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Educating your app – adding ML edge to your apps - Maoz Tamir

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PPT
Teaching material agriculture food technology
PDF
Empathic Computing: Creating Shared Understanding
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MYSQL Presentation for SQL database connectivity
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
Spectral efficient network and resource selection model in 5G networks
Unlocking AI with Model Context Protocol (MCP)
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
Teaching material agriculture food technology
Empathic Computing: Creating Shared Understanding
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
sap open course for s4hana steps from ECC to s4
Spectroscopy.pptx food analysis technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology

Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & Amichai Nitzan

  • 1. Think About Async Think Async Understanding the Complexity of Multi-Threading
  • 2. Who Are We? Avi Kabizon @avikabizon R&D Team Manager AppPulse Mobile R&D avi.kabizon@hpe.com Amichai Nitsan @aminits Senior Architect AppPulse Suite R&D amichai.nitsan@hpe.com
  • 3. . . . Our Day Job . . . –User Experience Monitoring: Performance Stability Usage Resource utilization –Tag-less and codeless –SaaS based, Free trial 3 saas.hpe.com/en-us/software/AppPulse-mobile
  • 4. 4 Motivation Async Patterns in Android Real World Examples Summary Agenda
  • 6. 6 Why Waiting Is Torture Alex Stone AUG. 18, 2012 http://www.nytimes.com/2012/08/19/opinion/sunday/why-waiting-in-line-is-torture.html
  • 7. Why Concurrency? 7 It is all about the User Experience Processing of data Waiting for server Housekeeping
  • 8. Android and Concurrency Pretty sure you all know but… – The UI thread is not allowed to access the network (a crash in StrictMode) … But also other long tasks are not allowed – Avoid the dreadful “Application Not Responding” (ANR) dialog: – Respond to a user action whithin 5 seconds – Finish executing a BroadcastReceiver within 10 seconds 8
  • 9. Android Application Responsiveness – An application should respond to any user action within 100 - 200 ms – “response” ≠ work is done – Indicate that “work is being done, and there is progress”  but entertain the users while they wait Make sure every user action is handled as fast as possible Users appreciate if you “take notes” and continue to serve them – Think Async: – Do users really need to wait for this image to upload? – Can the users start working with partial data? – Is the screen rendering waiting for unrelated actions? 9
  • 10. Thread Performance Isolation 10 – How are threads behaving? – Challenges with existing tools: – Debugger – Logs (System.err.println) – Traceview: – Capture button – Code tagging (android.os.Debug.startMethodTracing)
  • 11. Async Patterns In Android #PERFMATTERS @YouTube 11
  • 12. AsyncTask – Easy to use – Short tasks that update the UI – Tied to fragment or activity lifecycle – Android executes AsyncTask tasks serially by default 12 class AsyncTask // init UI onPreExecute() // start background doInBackground() // update UI onProgressUpdate() // Update UI onPostExecute() task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
  • 13. Loader 13 class CursorLoader // returns a cursor public Cursor loadInBackground() – Loads data from an external source into a local DB – Ideal for sync that is independent of user actions – Not tied to fragment or activity – Complex to use in code
  • 14. HandlerThread – A background thread for handling multiple jobs in the background – Runs outside of activity lifecycle – Long running processes – Need to manage lifecycle manually - call quit() – No built-in mechanism for reporting back – Set the right thread priority! 14 HandlerThread handlerThread = new HandlerThread("MyHandlerThread"); handlerThread.start(); Looper looper = handlerThread.getLooper(); Handler handler = new Handler(looper); … handler.post(new Runnable(){…});
  • 15. IntentService – HandlerThread runs as a Service – Handles incoming Intents on a separate process – Best for intents without foreground updates – Will block other incoming intents 15 class IntentService // Do work here onHandleIntent(Intent workIntent) <application> <service android:name=".MyService" android:exported="false"/> <application/>
  • 16. ThreadPoolExecutor – Manages a pool of worker threads – Tasks run in parallel – Powerful tool for demanding situations – Each thread consumes at least 64KB of mem – Need to find the magical min and max number of threads 16 ThreadPoolExecutor executor = new ThreadPoolExecutor(); executor.execute(new Runnable() { public void run() { // Do some long running } });
  • 17. Java Thread – Fine control on the details … but lots of code – Usually used as last resort 17 new Thread(new Runnable() { public void run() { // do background job } }).start(); JobScheduler SyncAdapter
  • 18. ThinkAsync – The Real World 18
  • 20. Think Network - Real world examples 20
  • 21. Think Async - Network Make a network call. No subsequent UI update. onclick() Network call Main doInbackground() User action: Submit registration form
  • 22. Think Async - Network Make a network call. Process the result and update UI. com.amazon.mShop.home.HomeView$2.onClick() com.amazon.rio.j2me.client.util.Worker.run() [POST] https://msh.amazon.com/mShop/service com.amazon.mShop.categoryBrowse.CategoryBrowseActivity.onResume() com.amazon.mShop.MShopActivity.onResume() com.amazon.mShop.android.AmazonActivity.onResume() … com.amazon.mShop.android.AmazonActivity$1.onAnimationStart() com.amazon.mShop.android.AmazonActivity$1.onAnimationEnd() … com.amazon.mShop.categoryBrowse.CategoryBrowseMainPageView$CategoryMainViewAdapter.g Main User action: Open Shop by department activity
  • 23. Think Async - Network Pattern analysis User action: Search cars
  • 24. Think Async - Network Pattern analysis onPostExecute() { … startAsyncTask(download); } User action: Search cars
  • 25. Think Async - Network “Stairs” pattern analysis • Creates new async task during onPostExecute() • No parallelism of HTTP calls • Thread creation overhead
  • 26. 26 Think Async - Network Handler thread User action: Open main activity Handler thread while (callable queue not empty) { runCallable (queue.poll); }
  • 27. 27 Think Async - Network Handler thread User action: Open main activity • Single thread performs multiple HTTP calls on same method • No thread creation overhead • Easier to make fewer HTTP calls
  • 28. Think Async - Network Thread per HTTP call com.amazon.mShop.android.net.HttpFetcher.run() [GET] http://ecx.images-amazon.com/images/I/51wxjlaS0qL._SL360_.jpg Method Network Sleep/Wait Scale: Main User action: Browse by category foreach (resource to download) { startAsyncTask(resource) }
  • 29. Think Async - Network Thread per HTTP call Parallelization of HTTP calls New thread for each HTTP call
  • 30. 30 Think Async - Network Thread pool Reused Threads User action: Open main tab
  • 31. Think Async - Network Thread pool Parallelization of http calls Efficient reuse of threads
  • 32. ThinkAsync – UI and Data 32
  • 33. Think UI Keep smooth UI by avoiding frame loss • Most Android devices refresh the screen 60 times a second • That means your code running on the UI thread has only ~16ms to: • Measure • Layout • Draw • Keep UI thread only for UI • Remember that all the on* methods run inside the UI Thread
  • 34. Think UI Speed up scrolling • Use Loaders • Use libraries, for example Glide or Picasso for image loading • Use RecyclerView or ListView with view holder pattern to avoid findViewById() calls
  • 35. Think UI Optimize animations • Avoid layout or inflation during animation • Watch out for lifecycle events • Avoid initiating animations in onCreate, onStart or onResume. • Initiate animations on user events such as onClick and disable touch events until animation is complete. • Don't initiate more than 2 animations simultaneously
  • 36. Think UI Animations in Think Async Fade in animation Shrink and grow animation Fragment.onResum e() Shrink and grow animation Fade in animation Layout change between animations Without layout change between animations
  • 39. Fighting to save the Digital User Experience Follow the adventures of the UX-Men: • AppPulse Active • AppPulse Mobile • AppPulse Trace 90% 1/3 saas.hpe.com/en-us/software/AppPulse-mobile