The importance of keeping the main thread free and ways to do it. We'll cover classic main thread busy pitfalls and classic workaround (IntentService, AsyncTask). We'll also cover useful techniques for getting back to the main thread and Simple synchronization strategies.
As presented in DroidCon Tel Aviv 2014 by:
Ori Peleg, Facebook
http://il.droidcon.com
5. Slow activity
▪ App was stuck
▪ ~5 seconds on older devices
▪ ANR :-(
▪ Computed items to display
6. Make it faster?
▪ The app was still stuck!
▪ Turns out we were Main Thread
bandits
▪ Any work done on the main
thread
▪ Prevents UI updates
▪ Prevents interaction (touch,
back button)
7. Make it seem faster!
▪ The app was still stuck!
▪ Turns out we were Main Thread
bandits
▪ Any work done on the main
thread
▪ Prevents UI updates
▪ Prevents interaction (touch,
back button)
▪ AsyncTask to the rescue!
9. Complex logic in the background
▪ “Make it a service”
▪ The app is super-slow
▪ “Separate process”
▪ The app isn’t stuck, but…
▪ Multi-process adds a lot of
complexity
10. Back to a single process
▪ App takes 10 seconds to load
▪ ANR :-(
▪ Can the service affect the UI’s
performance?
▪ (yes)
▪ Many dependent initialization
steps
▪ AsyncTask?
11. Threads
▪ Many things can happen in
parallel
▪ Main thread stays free
▪ But we create a lot of threads
14. Jank hunters
▪ We must fight to keep the
main thread free!
▪ Every Activity Service callback
is called in the main thread!
▪ Computations – too slow
▪ Network access – too slow
▪ Disk I/O?
▪ Even that is too slow
▪ StrictMode FTW
15. SharedPreferences
▪ In-memory cache
▪ Fast enough for the main
thread
▪ But what about editing?
▪ .commit() flushes to disk (can
block)
▪ No guarantees (no fsync)
▪ .apply() is good
16. Common patterns
▪ Loading images
▪ Picasso, by Square
▪ UI isn’t ready
▪ Progress indicator
▪ Some of the UI isn’t ready
▪ Show later (progress / fade in)
▪ Background processing
▪ IntentService (instead of Service)
17. Common errors
▪ Activity/Fragment have died
while processing
▪ Cancel work in onStop/
onDestroy
▪ Check isDestroyed/isAdded
▪ Thread-sensitive code
▪ ThreadLocal
28. Simple rules to follow
▪ Be aware what’s running on which thread
▪ Remember what’s slow
▪ Offload asynchronicity to libraries
▪ Test on typical (vs high-end) devices
▪ Threads/Executors/Futures FTW