SlideShare uma empresa Scribd logo
1 de 27
Android Programming




       Lesson 9
Multiple Background
      Threads
     NGUYEN The Linh
Android Programming


Contents



      1    Overview

      2    Using Handlers

      3    Using AsyncTask




                            2
Android Programming


Multiple Background Threads




                Overview




                    3
Android Programming


Overview

 When an application is launched, the system creates a
  thread of execution for the application, called "main."

 The main thread is also sometimes called the UI
  thread.

 The system does not create a separate thread for each
  instance of a component. All components that run in
  the same process are instantiated in the UI thread,
  and system calls to each component are dispatched
  from that thread.
                           4
Android Programming


Overview

 If everything is happening in the UI thread,
  performing long operations such as network access or
  database queries will block the whole UI.



 When the thread is blocked, no events can be
  dispatched, including drawing events.




                          5
Android Programming


Overview

 Even worse, if the UI thread is blocked for more than a
  few seconds (about 5 seconds currently) the user is
  presented with the infamous "application not
  responding" (ANR) dialog.




                           6
Android Programming


Overview

 The user might then decide to quit your application
  and uninstall it if they are unhappy.




                          7
Android Programming


Overview

 There are simply two rules to Android's single thread
  model:
    Do not block the UI thread
    Do not access the Android UI toolkit from outside the UI thread




                                 8
Android Programming


Multiple Background Threads




              Using Handlers




                    9
Android Programming


Using Handlers

 Do not block the UI thread
    Because of the single thread model described above, it's vital to
     the responsiveness of your application's UI that you do not block
     the UI thread. If you have operations to perform that are not
     instantaneous, you should make sure to do them in separate
     threads ("background" or "worker" threads).




                                 10
Android Programming


Using Handlers

 Do not block the UI thread




                          11
Android Programming


Using Handlers

 Do not block the UI thread
    At first, this seems to work fine, because it creates a new thread to
     handle the network operation. However, it violates the second rule
     of the single-threaded model: do not access the Android UI toolkit
     from outside the UI thread—this sample modifies
     the ImageView from the worker thread instead of the UI thread.

     This can result in undefined and unexpected behavior, which can
      be difficult and time-consuming to track down.



                                  12
Android Programming


Using Handlers

 Do not block the UI thread
    To fix this problem, Android offers several ways to access the UI
     thread from other threads. Here is a list of methods that can help:
        • Activity.runOnUiThread(Runnable)
        • View.post(Runnable)
        • View.postDelayed(Runnable, long)




                                     13
Android Programming


Using Handlers

 Do not block the UI thread




                          14
Android Programming


Using Handlers

 Do not block the UI thread
    To handle more complex interactions with a worker thread, you
     might consider using a Handler in your worker thread, to process
     messages delivered from the UI thread.




                                 15
Android Programming


Using Handlers


Worker Thread              UI Thread




                 Handler



                   16
Android Programming


Using Handlers


Worker Thread




                 Handler



                   17
Android Programming


Using Handlers

 Example 9.1
    Using Handlers




                      18
Android Programming


Multiple Background Threads




             Using AsyncTask




                    19
Android Programming


Using AsyncTask

 AsyncTask is an abstract class that provides several
  methods managing the interaction between the UI
  thread and the background thread.

 It’s implementation is by creating a sub class that
  extends AsyncTask and implementing the different
  protected methods it provides.




                          20
Android Programming


Using AsyncTask

 Step 1 is creating the AsyncTask sub class:
    class ProgressTask extends AsyncTask<Params, Progress,
     Result>{ }
    Params: parameter info passed to be used by the AsyncTask.
    Progress: the type of progress that the task accomplishes.
    The result returned after the AsyncTask finishes.




                              21
Android Programming


Using AsyncTask

 Step 1 is creating the AsyncTask sub class:
    class ProgressTask extends AsyncTask<Integer, Integer,
     Void>{ }
    The parameter and the progress are of type Integer and the result
     is Void as our tasks does not return anything (return null).




                                 22
Android Programming


Using AsyncTask

 Step 2 is overriding the protected methods defined by
  the AsyncTask class that handle the execution life
  cycle of the AsyncTask.
    We have five methods to implement which are:
      • onPreExecute: the first method called in the AsyncTask, called on the UI
        thread.

      • doInBackground: the method that executes the time consuming tasks and
        publish the task progress, executed in background thread.




                                      23
Android Programming


Using AsyncTask

 Step 2
    We have five methods to implement which are:

       • onProgressUpdate: method that updates the progress of the AsyncTask, run
         on the UI thread.

       • onPostExecute: the final method that gets called
         after doInBackground finishes, here we can update the UI with the results of
         the AsyncTask.

       • onCancelled: gets called if the AsyncTask.cancel() methods is called,
         terminating the execution of the AsyncTask.

                                       24
Android Programming


Using AsyncTask

 Step 3
    Execute
      • ProgressTask task=new ProgressTask();
      • task.execute(10);


    Cancel
      • task.cancel(true);




                                   25
Android Programming


Using AsyncTask

 Example 9.2
    Using AsyncTask




                       26
Android Programming

Mais conteúdo relacionado

Semelhante a [Android] Multiple Background Threads

MobileAppDev Handout#4
MobileAppDev Handout#4MobileAppDev Handout#4
MobileAppDev Handout#4trupti1976
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answerskavinilavuG
 
Google I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackGoogle I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackSunita Singh
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2Paramvir Singh
 
React_Complete.pptx
React_Complete.pptxReact_Complete.pptx
React_Complete.pptxkamalakantas
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operationMatteo Bonifazi
 
An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...William Liang
 
Android Application Development for Intel Platform
Android Application Development for Intel PlatformAndroid Application Development for Intel Platform
Android Application Development for Intel PlatformAtifAliHaral
 
Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App DevelopmentAbhijeet Gupta
 
Android internals
Android internalsAndroid internals
Android internalsrabah3
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
 
Android best training-in-mumbai
Android best training-in-mumbaiAndroid best training-in-mumbai
Android best training-in-mumbaivibrantuser
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...Padma shree. T
 

Semelhante a [Android] Multiple Background Threads (20)

MobileAppDev Handout#4
MobileAppDev Handout#4MobileAppDev Handout#4
MobileAppDev Handout#4
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
 
Android Basics
Android BasicsAndroid Basics
Android Basics
 
Google I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackGoogle I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and Jetpack
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
 
React_Complete.pptx
React_Complete.pptxReact_Complete.pptx
React_Complete.pptx
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...An Introduction to the Android Framework -- a core architecture view from app...
An Introduction to the Android Framework -- a core architecture view from app...
 
My android
My androidMy android
My android
 
My android
My androidMy android
My android
 
Android Application Development for Intel Platform
Android Application Development for Intel PlatformAndroid Application Development for Intel Platform
Android Application Development for Intel Platform
 
Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App Development
 
Android internals
Android internalsAndroid internals
Android internals
 
Best Android Course
Best Android CourseBest Android Course
Best Android Course
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Unit I- ANDROID OVERVIEW.ppt
Unit I- ANDROID OVERVIEW.pptUnit I- ANDROID OVERVIEW.ppt
Unit I- ANDROID OVERVIEW.ppt
 
Android best training-in-mumbai
Android best training-in-mumbaiAndroid best training-in-mumbai
Android best training-in-mumbai
 
Android the future
Android  the futureAndroid  the future
Android the future
 
All about android
All about androidAll about android
All about android
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
 

Mais de Nikmesoft Ltd

[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background ThreadsNikmesoft Ltd
 
[iOS] Basic UI Elements
[iOS] Basic UI Elements[iOS] Basic UI Elements
[iOS] Basic UI ElementsNikmesoft Ltd
 
[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS ProgrammingNikmesoft Ltd
 
[Android] Multimedia Programming
[Android] Multimedia Programming[Android] Multimedia Programming
[Android] Multimedia ProgrammingNikmesoft Ltd
 
[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android AnimationNikmesoft Ltd
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D GraphicsNikmesoft Ltd
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast ReceiversNikmesoft Ltd
 
[Android] Web services
[Android] Web services[Android] Web services
[Android] Web servicesNikmesoft Ltd
 
[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based ServicesNikmesoft Ltd
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data StorageNikmesoft Ltd
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and ActivityNikmesoft Ltd
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event HandlingNikmesoft Ltd
 
[Android] Using Selection Widgets
[Android] Using Selection Widgets[Android] Using Selection Widgets
[Android] Using Selection WidgetsNikmesoft Ltd
 
[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers[Android] Basic Widgets and Containers
[Android] Basic Widgets and ContainersNikmesoft Ltd
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android ProgrammingNikmesoft Ltd
 

Mais de Nikmesoft Ltd (18)

[iOS] Networking
[iOS] Networking[iOS] Networking
[iOS] Networking
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background Threads
 
[iOS] Navigation
[iOS] Navigation[iOS] Navigation
[iOS] Navigation
 
[iOS] Basic UI Elements
[iOS] Basic UI Elements[iOS] Basic UI Elements
[iOS] Basic UI Elements
 
[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming
 
[Android] Multimedia Programming
[Android] Multimedia Programming[Android] Multimedia Programming
[Android] Multimedia Programming
 
[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android Animation
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D Graphics
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers
 
[Android] Web services
[Android] Web services[Android] Web services
[Android] Web services
 
[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event Handling
 
[Android] Using Selection Widgets
[Android] Using Selection Widgets[Android] Using Selection Widgets
[Android] Using Selection Widgets
 
[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android Programming
 

Último

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Último (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

[Android] Multiple Background Threads

  • 1. Android Programming Lesson 9 Multiple Background Threads NGUYEN The Linh
  • 2. Android Programming Contents 1 Overview 2 Using Handlers 3 Using AsyncTask 2
  • 4. Android Programming Overview  When an application is launched, the system creates a thread of execution for the application, called "main."  The main thread is also sometimes called the UI thread.  The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. 4
  • 5. Android Programming Overview  If everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI.  When the thread is blocked, no events can be dispatched, including drawing events. 5
  • 6. Android Programming Overview  Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. 6
  • 7. Android Programming Overview  The user might then decide to quit your application and uninstall it if they are unhappy. 7
  • 8. Android Programming Overview  There are simply two rules to Android's single thread model:  Do not block the UI thread  Do not access the Android UI toolkit from outside the UI thread 8
  • 9. Android Programming Multiple Background Threads Using Handlers 9
  • 10. Android Programming Using Handlers  Do not block the UI thread  Because of the single thread model described above, it's vital to the responsiveness of your application's UI that you do not block the UI thread. If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads). 10
  • 11. Android Programming Using Handlers  Do not block the UI thread 11
  • 12. Android Programming Using Handlers  Do not block the UI thread  At first, this seems to work fine, because it creates a new thread to handle the network operation. However, it violates the second rule of the single-threaded model: do not access the Android UI toolkit from outside the UI thread—this sample modifies the ImageView from the worker thread instead of the UI thread.  This can result in undefined and unexpected behavior, which can be difficult and time-consuming to track down. 12
  • 13. Android Programming Using Handlers  Do not block the UI thread  To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: • Activity.runOnUiThread(Runnable) • View.post(Runnable) • View.postDelayed(Runnable, long) 13
  • 14. Android Programming Using Handlers  Do not block the UI thread 14
  • 15. Android Programming Using Handlers  Do not block the UI thread  To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, to process messages delivered from the UI thread. 15
  • 16. Android Programming Using Handlers Worker Thread UI Thread Handler 16
  • 18. Android Programming Using Handlers  Example 9.1  Using Handlers 18
  • 19. Android Programming Multiple Background Threads Using AsyncTask 19
  • 20. Android Programming Using AsyncTask  AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread.  It’s implementation is by creating a sub class that extends AsyncTask and implementing the different protected methods it provides. 20
  • 21. Android Programming Using AsyncTask  Step 1 is creating the AsyncTask sub class:  class ProgressTask extends AsyncTask<Params, Progress, Result>{ }  Params: parameter info passed to be used by the AsyncTask.  Progress: the type of progress that the task accomplishes.  The result returned after the AsyncTask finishes. 21
  • 22. Android Programming Using AsyncTask  Step 1 is creating the AsyncTask sub class:  class ProgressTask extends AsyncTask<Integer, Integer, Void>{ }  The parameter and the progress are of type Integer and the result is Void as our tasks does not return anything (return null). 22
  • 23. Android Programming Using AsyncTask  Step 2 is overriding the protected methods defined by the AsyncTask class that handle the execution life cycle of the AsyncTask.  We have five methods to implement which are: • onPreExecute: the first method called in the AsyncTask, called on the UI thread. • doInBackground: the method that executes the time consuming tasks and publish the task progress, executed in background thread. 23
  • 24. Android Programming Using AsyncTask  Step 2  We have five methods to implement which are: • onProgressUpdate: method that updates the progress of the AsyncTask, run on the UI thread. • onPostExecute: the final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask. • onCancelled: gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask. 24
  • 25. Android Programming Using AsyncTask  Step 3  Execute • ProgressTask task=new ProgressTask(); • task.execute(10);  Cancel • task.cancel(true); 25
  • 26. Android Programming Using AsyncTask  Example 9.2  Using AsyncTask 26