SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Similaire à [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
 

Similaire à [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 ...
 

Plus 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
 

Plus 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
 

Dernier

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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 WorkerThousandEyes
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 

Dernier (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 

[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