SlideShare a Scribd company logo
1 of 14
Android
Thread, Handler and AsyncTask
                        Hoang Ngo
Thread
   • Act much like usual Java Threads

   • Can’t act directly on external User
     Interface objects (throw the Exception
     CalledFromWrongThreadException: Only
     the original thread that created a view
     hierarchy can touch its views”)
   • Can’t be stopped by executing destroy()
     nor stop(). Use instead interrupt() or join()
     (by case)
Thread
   • Two main ways of having a Thread
     execute application code:
     – Providing a new class that extends Thread and
       overriding its run() method.
     – Providing a new Thread instance with a
       Runnable object during its creation. In both
       cases, the start() method must be called to
       actually execute the new Thread.
Thread example
Handler

   • Associated with a single thread and
     that thread's message queue
   • Bound to the thread / message
     queue of the thread that is creating it
   • Deliver messages and runnables to
     that message queue
   • Execute them as they come out of
     the message queue
Handler

   • Two main uses for a Handler:
     – To schedule messages and
       runnables to be executed as some
       point in the future
     – To add an action into a queue
       performed on a different thread
Handler example
AsyncTask
    • Created on the UI thread and can be executed
      only once

    • Run on a background thread and result is
      published on the UI thread

    • The three types used by an asynchronous task
      are the following
       – Params, the type of the parameters sent to the task
         upon execution
       – Progress, the type of the progress units published during
         the background computation
       – Result, the type of the result of the background
         computation

    • Extend AsyncTask<Void, Void, Void>
AsyncTask
   • Go through 4 steps:
     – onPreExecute(): invoked on the UI thread
       immediately after the task is executed
     – doInBackground(Param ...): invoked on the
       background thread immediately after
       onPreExecute() finishes executing
     – onProgressUpdate(Progress...): invoked on the
       UI thread after a call to
       publishProgress(Progress...)
     – onPostExecute(Result): invoked on the UI
       thread after the background computation
       finishes
AsyncTask example
•   Violate the single thread model: the Android UI toolkit is not
    thread-safe and must always be manipulated on the UI thread.
•   In this piece of code, the ImageView is manipulated on a
    worker thread, which can cause really weird problems. Tracking
    down and fixing such bugs can be difficult and time-consuming
•   Classes and methods also tend to make the code more
    complicated and more difficult to read.
•   It becomes even worse when our implement complex
    operations that require frequent UI updates
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask

More Related Content

What's hot

Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
connectshilpa
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Opersys inc.
 

What's hot (20)

Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Android Presentation
Android PresentationAndroid Presentation
Android Presentation
 
Software Engineering - chp3- design
Software Engineering - chp3- designSoftware Engineering - chp3- design
Software Engineering - chp3- design
 
Mobile Application Development With Android
Mobile Application Development With AndroidMobile Application Development With Android
Mobile Application Development With Android
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Basic Android College Seminar Presentation
Basic Android College Seminar Presentation Basic Android College Seminar Presentation
Basic Android College Seminar Presentation
 
Android Operating System
Android Operating SystemAndroid Operating System
Android Operating System
 
Symbian Operating system
Symbian Operating systemSymbian Operating system
Symbian Operating system
 
Mobile application development ppt
Mobile application development pptMobile application development ppt
Mobile application development ppt
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Android PPT Presentation 2018
Android PPT Presentation 2018Android PPT Presentation 2018
Android PPT Presentation 2018
 
Android notification
Android notificationAndroid notification
Android notification
 
DATA PERSISTENCE IN ANDROID OPERATING SYSTEM
DATA PERSISTENCE IN ANDROID OPERATING SYSTEMDATA PERSISTENCE IN ANDROID OPERATING SYSTEM
DATA PERSISTENCE IN ANDROID OPERATING SYSTEM
 
Evolution of android operating system
Evolution of android operating systemEvolution of android operating system
Evolution of android operating system
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
Google Maps in Android
Google Maps in AndroidGoogle Maps in Android
Google Maps in Android
 
Android ppt
 Android ppt Android ppt
Android ppt
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
 
Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 

Similar to Android - Thread, Handler and AsyncTask

Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 

Similar to Android - Thread, Handler and AsyncTask (20)

Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Scheduling Thread
Scheduling  ThreadScheduling  Thread
Scheduling Thread
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Java threads
Java threadsJava threads
Java threads
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdf
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
0903 1
0903 10903 1
0903 1
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multithreading and concurrency.pptx
Multithreading and concurrency.pptxMultithreading and concurrency.pptx
Multithreading and concurrency.pptx
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
 
Operating System lab
Operating System labOperating System lab
Operating System lab
 
Android async task
Android async taskAndroid async task
Android async task
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Android - Thread, Handler and AsyncTask

  • 1. Android Thread, Handler and AsyncTask Hoang Ngo
  • 2. Thread • Act much like usual Java Threads • Can’t act directly on external User Interface objects (throw the Exception CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views”) • Can’t be stopped by executing destroy() nor stop(). Use instead interrupt() or join() (by case)
  • 3. Thread • Two main ways of having a Thread execute application code: – Providing a new class that extends Thread and overriding its run() method. – Providing a new Thread instance with a Runnable object during its creation. In both cases, the start() method must be called to actually execute the new Thread.
  • 5. Handler • Associated with a single thread and that thread's message queue • Bound to the thread / message queue of the thread that is creating it • Deliver messages and runnables to that message queue • Execute them as they come out of the message queue
  • 6. Handler • Two main uses for a Handler: – To schedule messages and runnables to be executed as some point in the future – To add an action into a queue performed on a different thread
  • 8. AsyncTask • Created on the UI thread and can be executed only once • Run on a background thread and result is published on the UI thread • The three types used by an asynchronous task are the following – Params, the type of the parameters sent to the task upon execution – Progress, the type of the progress units published during the background computation – Result, the type of the result of the background computation • Extend AsyncTask<Void, Void, Void>
  • 9. AsyncTask • Go through 4 steps: – onPreExecute(): invoked on the UI thread immediately after the task is executed – doInBackground(Param ...): invoked on the background thread immediately after onPreExecute() finishes executing – onProgressUpdate(Progress...): invoked on the UI thread after a call to publishProgress(Progress...) – onPostExecute(Result): invoked on the UI thread after the background computation finishes
  • 11. Violate the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. • In this piece of code, the ImageView is manipulated on a worker thread, which can cause really weird problems. Tracking down and fixing such bugs can be difficult and time-consuming
  • 12. Classes and methods also tend to make the code more complicated and more difficult to read. • It becomes even worse when our implement complex operations that require frequent UI updates