MobApp 20 - Threads in Android
MobApp 20 - Threads in Android
Arfan Shahzad
{ [email protected] }
Mobile Application Development
Threading
• It’s super easy and simple to use it’s also good for some basic
scenarios:
Threading
cont…
Attached to
an activity/
fragment:
ASYNCTASK
Threading cont…
Attached to an activity/fragment: ASYNCTASK
• AsyncTask, however, falls short if you would like your deferred task to
run beyond the lifetime of the activity/fragment.
• The fact that even the slightest of screen rotation can cause the
activity to be destroyed is simply awful!
• So We Come to Loaders:
Threading cont…
Attached to an activity/fragment: LOADERS
• Loaders are the answer to the awful nightmare mentioned above.
• Service runs within the main thread of its hosting process; the service
doesn’t create its own thread and doesn’t run during a separate
process unless you specify otherwise.
Threading cont…
Not attached to an activity/fragment: SERVICE
Threading cont…
Not attached to an activity/fragment: SERVICE
• Service could be thought of as a component that’s useful for
performing long (or potentially long) operations with no UI.
• Service runs within the main thread of its hosting process; the service
doesn’t create its own thread and doesn’t run during a separate
process unless you specify otherwise.
Threading cont…
Not attached to an activity/fragment: SERVICE
• Service could be thought of as a component that’s useful for
performing long (or potentially long) operations with no UI.
• Service runs within the main thread of its hosting process; the service
doesn’t create its own thread and doesn’t run during a separate
process unless you specify otherwise.
Threading cont…
1. Main Thread
2. UI Thread
3. Worker Thread
4. Any Thread
5. Binder Thread
Threading cont…
Main Thread
• When we launch our app on Android, it creates the first thread of
execution called the “Main Thread”.
• The UI thread is the main thread of execution for our app as this is
where most of the app code is run.
Threading cont…
UI Thread
• The UI thread is where all of our app components (like activities,
services, content providers, and broadcast receivers) are created.
• This thread allows our tasks to perform their background work and
then move the results to UI elements such as bitmaps.
• The worker threads are created separately, other than threads like the
UI thread.
• If the annotated element is a class, then all methods in the class can
be called from Any Thread.
Threading cont…
Any Thread
Threading cont…
Binder Thread
• Binder thread represents a separate thread of service.