Android Threading
Charlie Tsai @ Android Study Group
Charlie Tsai @ Android Study Group
cha122977@gmail.com
Software Engineer
Today’s source code
throws new NullPointerException()
Agenda
• Background Knowledge
• Android Thread
• Free Discussions :P
Background
Knowledge
What is Thread?
• Process
• Process vs Thread
• Thread and Process of JVM
• Multithreading vs Multi-process
• Kernel Task
Issues of Multithreading
• Race condition (Synchronization issue)
• Dead lock issue
• Interaction of Thread
• Hard to testing
Android Thread
Android Thread
• UI Thread (==Main Thread) & Worker Thread
• Looper, MessageQueue, and Handler
• UI Refreshing
• ActivityThread.java
• ViewRootImpl.java
• Choreographer.java
Useful APIs
• View.post() & runOnUiThread()
• Thread & Runnable
• Executor & Runnable
• Future & Callable
• Handler & HanderThread
• AsyncTask
• IntentService
• AsyncLoader
View.post() &
runOnUiThread()
• Pros
• Easy to use
• Make function adaptive
• Cons
• May cause callback hell
Thread & Runnable
• Pros
• Easy to use
• Fully control
• Cons
• Fully control
• No return value
• Data synchronization issue
Executor & Runnable
• Pros
• Easy to use
• Avoid too much instances of Thread
• Cons
• No return value
Future & Callable
• Pros
• Easy to use
• Have return value
• Cons
• Get return value may block UI Thread
Bad Usage
Handler & HandlerThread
• Pros
• Easy to use
• Easy to communication between threads
• Cons
• Need to implement switch-case of Handler
• Limitation of data type
AsyncTask
• Pros
• Progress Updating
• Easy to cancel
• onPostExecute run in UI Thread
• Cons
• Duplicated codes
• Hard to trace code
IntentService
• Pros
• Easy to use
• Not depends on Activity
• Cons
• No return value
• Limitation of data type
AsyncLoader
• Pros
• Easy to manager multiple Loaders
• Asynchronous
• Clear to read
• Cons
• Need to implement callback interface
• Only for Activity & Fragment
• Hard to use
Free Discussions! :P
ResultReceiver
• Implement Parcelable
• Can be used to return values
• Use Bundle to carry the data
• Can send data multiple times
Request Side
Return (Result) Side
Android Multiple
Processes
Enable Multiple Processes
• android:process=“:newProcessName”
• startService() and/or bindService()
IPC & RFC
• Inter-Process Communication
• Remote Function Call (*RemoteException)
• ContentProvider & ContentReslover
• Bound service + Messenger
• Bound service + AIDL
Parcel
Parcel
• Why Parcel?
• Parcelable
• AIDL
• Bundle.putParcelable()
• Message.obj
工商時間的說
December 3rd @ 台灣大學普通教學館
固定聚會:每週三@果子咖啡(近捷運南京復興站)
技術分享:每月底週六14:30 - 17:30
以及眾多不定期活動(ex: Workshop)
Questions?
Thanks!

Android Thread