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

What's hot (20)

Manipulating Android tasks and back stack
Manipulating Android tasks and back stackManipulating Android tasks and back stack
Manipulating Android tasks and back stack
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Hibernate notes
Hibernate notesHibernate notes
Hibernate notes
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Express js
Express jsExpress js
Express js
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Android activities & views
Android activities & viewsAndroid activities & views
Android activities & views
 
Fragment
Fragment Fragment
Fragment
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Introduction to Eclipse IDE
Introduction to Eclipse IDEIntroduction to Eclipse IDE
Introduction to Eclipse IDE
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
Reactjs workshop
Reactjs workshop Reactjs workshop
Reactjs workshop
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 

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

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

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