SlideShare a Scribd company logo
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

More Related Content

Similar to [Android] Multiple Background Threads

MobileAppDev Handout#4
MobileAppDev Handout#4MobileAppDev Handout#4
MobileAppDev Handout#4
trupti1976
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
kavinilavuG
 
Android Basics
Android BasicsAndroid Basics
Android Basics
Krushnakant Solanki
 
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
Sunita Singh
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
Paramvir Singh
 
React_Complete.pptx
React_Complete.pptxReact_Complete.pptx
React_Complete.pptx
kamalakantas
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
Matteo 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
 
My android
My androidMy android
My android
Prince Bhanwra
 
My android
My androidMy android
My android
Prince Bhanwra
 
Android Application Development for Intel Platform
Android Application Development for Intel PlatformAndroid Application Development for Intel Platform
Android Application Development for Intel Platform
AtifAliHaral
 
Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App Development
Abhijeet Gupta
 
Android internals
Android internalsAndroid internals
Android internals
rabah3
 
Best Android Course
Best Android CourseBest Android Course
Best Android Course
bestonlinecoursescoupon
 
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
Utkarsh Mankad
 
Unit I- ANDROID OVERVIEW.ppt
Unit I- ANDROID OVERVIEW.pptUnit I- ANDROID OVERVIEW.ppt
Unit I- ANDROID OVERVIEW.ppt
dineshkumar periyasamy
 
Android best training-in-mumbai
Android best training-in-mumbaiAndroid best training-in-mumbai
Android best training-in-mumbai
vibrantuser
 
Android the future
Android  the futureAndroid  the future
Android the future
Sanjeev Kumar Jaiswal
 
All about android
All about androidAll about android
All about android
Inimitable Harish
 
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
 

Similar to [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 ...
 

More from Nikmesoft Ltd

[iOS] Networking
[iOS] Networking[iOS] Networking
[iOS] Networking
Nikmesoft Ltd
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
Nikmesoft Ltd
 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background Threads
Nikmesoft Ltd
 
[iOS] Navigation
[iOS] Navigation[iOS] Navigation
[iOS] Navigation
Nikmesoft Ltd
 
[iOS] Basic UI Elements
[iOS] Basic UI Elements[iOS] Basic UI Elements
[iOS] Basic UI Elements
Nikmesoft Ltd
 
[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming
Nikmesoft Ltd
 
[Android] Multimedia Programming
[Android] Multimedia Programming[Android] Multimedia Programming
[Android] Multimedia Programming
Nikmesoft Ltd
 
[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android Animation
Nikmesoft Ltd
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D Graphics
Nikmesoft Ltd
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers
Nikmesoft Ltd
 
[Android] Web services
[Android] Web services[Android] Web services
[Android] Web services
Nikmesoft 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 Services
Nikmesoft Ltd
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
Nikmesoft Ltd
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
Nikmesoft Ltd
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event Handling
Nikmesoft Ltd
 
[Android] Using Selection Widgets
[Android] Using Selection Widgets[Android] Using Selection Widgets
[Android] Using Selection Widgets
Nikmesoft Ltd
 
[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers
Nikmesoft Ltd
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android Programming
Nikmesoft Ltd
 

More from 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
 

Recently uploaded

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 

[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