SlideShare uma empresa Scribd logo
1 de 21
Today’s Manifest
Concurrency
● Android’s thread model
● Using concurrency
o AsyncTasks
o Handlers
● Adverse effects
Android Thread Model
● Android uses a single thread to do all work
● That single thread, runs the user interface
o Thus, its called the UI Thread
● All code we write in Activity lifecycle events /
Broadcasts / Services are running in the UI
Thread
Android Thread model
● Doing extensive work on the UI thread will
slow down UI components
o e.g. When the thread does a heavy database query,
clicking the buttons cannot be done.!
● UI will become unresponsive
● Happens because UI thread can’t refresh
items while doing other work on itself.
Android Thread model
● When the UI becomes unresponsive,
Android takes action
● First is to show the “Application Not
Responding” dialog (ANR)
● Happens within 5 seconds of unresponsive
UI
Android Thread model
● If the user choses to wait
o Android tolerates for another 20s
● The message will continue to occur
● To prevent that, we need to use any one of
multiple concurrency methods in Android
Lets start coding
Stage 1
● Setup simple task in the form of a
Thread.sleep()
● Try getting an output from that task and
putting it to UI
● Try clicking UI items while at it.
o See the ANR?
Stage 2
● So the UI thread is the problem!
● Create another Thread. Java to the rescue.!
● Try setting the UI.
o Yes, its supposed to be that way. Don’t panic
Stage 3
● UI components can be updated in UI thread
● So use runOnUiThread()
● Problem solved. Or...is it?
● Try to get repetitive tasks to run with an
update.
o Code looks ugly? Indeed.
Stage 4
● Use AsyncTask for the same process
o Click
o Notify
o Update
o Finish
AsyncTask
● Executes in a different Thread than the UI
thread.
● Suitable for small, couple of second
operations
● All AsyncTasks run in one Thread at the OS
level.
AsyncTask
● Four segments
o Pre execute
o Do in background
o On update
o Post execute
● All others except doInBackground() are
run on the UI thread.
● doInBackground() is run in the parallel
AsyncTask thread.
Stage 4
● Done deal.? Not so fast
● AsyncTask cannot be used in every case.
● Long running executions should be done
using ThreadPoolExecutor and
FutureTask
o Better left for another session
● To make matters worse, AsyncTask has
some issues as well.
Issues with AsyncTask
● Run the same app, but this time, rotate the
screen while the task is going.!
● In order to prevent that, we need to either
o Lock screen orientation (at least while in task)
o Use Fragments
● Of course we’re going to use Fragments.
Who asked that question?
Stage 5
● Create a dummy (blank) Fragment with no
UI, but our AsyncTask
● Make sure to call setRetainInstance(true);
● Use a local variable to re-initiate the
progress dialogs if needed.
Handler
● A Handler can be used to receive messages
from other threads
● The handler resides in the UI thread and
updates the UI components accordingly
Stage 6
● Use the usual Activity with a new Thread
● Run the Thread and pass a message to a
Handler in the Activity
Confused?
you should be….!
is here
https://github.com/tdevinda/DialogAndroidIntro_3
Check branches asynctask and handler
(you will need git)
Final Code
Introduction to Android - Session 3

Mais conteúdo relacionado

Semelhante a Introduction to Android - Session 3

Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadinPetter Holmström
 
Insights on Protractor testing
Insights on Protractor testingInsights on Protractor testing
Insights on Protractor testingDejan Toteff
 
Shake that-fud-vrs5
Shake that-fud-vrs5Shake that-fud-vrs5
Shake that-fud-vrs5wimjongman
 
Full stack development
Full stack developmentFull stack development
Full stack developmentArnav Gupta
 
Lecture #2 threading, networking & permissions final version #2
Lecture #2  threading, networking & permissions final version #2Lecture #2  threading, networking & permissions final version #2
Lecture #2 threading, networking & permissions final version #2Vitali Pekelis
 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background ThreadsNikmesoft Ltd
 
Threading model in windows store apps
Threading model in windows store appsThreading model in windows store apps
Threading model in windows store appsMirco Vanini
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2Paramvir Singh
 
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)Daniel Juyung Seo
 
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...Iosif Itkin
 
Campkde 2010: KDE Plasma netbook
Campkde 2010: KDE Plasma netbookCampkde 2010: KDE Plasma netbook
Campkde 2010: KDE Plasma netbookMarco Martin
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React NativeDamian Zbrożek
 
A sip of elixir
A sip of elixirA sip of elixir
A sip of elixirUttam Kini
 
Introduction to Continuous Delivery
Introduction to Continuous DeliveryIntroduction to Continuous Delivery
Introduction to Continuous DeliveryGiovanni Toraldo
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.jsvaluebound
 
New generation Linux distributions that companion with Geeko : opencocon and...
New generation Linux distributions that companion with Geeko :  opencocon and...New generation Linux distributions that companion with Geeko :  opencocon and...
New generation Linux distributions that companion with Geeko : opencocon and...shimadah
 
All Aboard The Stateful Train
All Aboard The Stateful TrainAll Aboard The Stateful Train
All Aboard The Stateful TrainSmartLogic
 

Semelhante a Introduction to Android - Session 3 (20)

Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadin
 
Insights on Protractor testing
Insights on Protractor testingInsights on Protractor testing
Insights on Protractor testing
 
Shake that-fud-vrs5
Shake that-fud-vrs5Shake that-fud-vrs5
Shake that-fud-vrs5
 
Full stack development
Full stack developmentFull stack development
Full stack development
 
Lecture #2 threading, networking & permissions final version #2
Lecture #2  threading, networking & permissions final version #2Lecture #2  threading, networking & permissions final version #2
Lecture #2 threading, networking & permissions final version #2
 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background Threads
 
Mobi Vision 2.0
Mobi Vision 2.0Mobi Vision 2.0
Mobi Vision 2.0
 
Threading model in windows store apps
Threading model in windows store appsThreading model in windows store apps
Threading model in windows store apps
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
 
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)
Improving Cross Desktop Standard by Cedric BAIL (GNOME Asia Summit 2013)
 
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...
TMPA-2017: Unity Application Testing Automation with Appium and Image Recogni...
 
Campkde 2010: KDE Plasma netbook
Campkde 2010: KDE Plasma netbookCampkde 2010: KDE Plasma netbook
Campkde 2010: KDE Plasma netbook
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React Native
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
A sip of elixir
A sip of elixirA sip of elixir
A sip of elixir
 
Introduction to Continuous Delivery
Introduction to Continuous DeliveryIntroduction to Continuous Delivery
Introduction to Continuous Delivery
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
 
New generation Linux distributions that companion with Geeko : opencocon and...
New generation Linux distributions that companion with Geeko :  opencocon and...New generation Linux distributions that companion with Geeko :  opencocon and...
New generation Linux distributions that companion with Geeko : opencocon and...
 
Background Thread
Background ThreadBackground Thread
Background Thread
 
All Aboard The Stateful Train
All Aboard The Stateful TrainAll Aboard The Stateful Train
All Aboard The Stateful Train
 

Último

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Último (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Introduction to Android - Session 3

  • 1.
  • 2. Today’s Manifest Concurrency ● Android’s thread model ● Using concurrency o AsyncTasks o Handlers ● Adverse effects
  • 3. Android Thread Model ● Android uses a single thread to do all work ● That single thread, runs the user interface o Thus, its called the UI Thread ● All code we write in Activity lifecycle events / Broadcasts / Services are running in the UI Thread
  • 4. Android Thread model ● Doing extensive work on the UI thread will slow down UI components o e.g. When the thread does a heavy database query, clicking the buttons cannot be done.! ● UI will become unresponsive ● Happens because UI thread can’t refresh items while doing other work on itself.
  • 5. Android Thread model ● When the UI becomes unresponsive, Android takes action ● First is to show the “Application Not Responding” dialog (ANR) ● Happens within 5 seconds of unresponsive UI
  • 6. Android Thread model ● If the user choses to wait o Android tolerates for another 20s ● The message will continue to occur ● To prevent that, we need to use any one of multiple concurrency methods in Android
  • 8. Stage 1 ● Setup simple task in the form of a Thread.sleep() ● Try getting an output from that task and putting it to UI ● Try clicking UI items while at it. o See the ANR?
  • 9. Stage 2 ● So the UI thread is the problem! ● Create another Thread. Java to the rescue.! ● Try setting the UI. o Yes, its supposed to be that way. Don’t panic
  • 10. Stage 3 ● UI components can be updated in UI thread ● So use runOnUiThread() ● Problem solved. Or...is it? ● Try to get repetitive tasks to run with an update. o Code looks ugly? Indeed.
  • 11. Stage 4 ● Use AsyncTask for the same process o Click o Notify o Update o Finish
  • 12. AsyncTask ● Executes in a different Thread than the UI thread. ● Suitable for small, couple of second operations ● All AsyncTasks run in one Thread at the OS level.
  • 13. AsyncTask ● Four segments o Pre execute o Do in background o On update o Post execute ● All others except doInBackground() are run on the UI thread. ● doInBackground() is run in the parallel AsyncTask thread.
  • 14. Stage 4 ● Done deal.? Not so fast ● AsyncTask cannot be used in every case. ● Long running executions should be done using ThreadPoolExecutor and FutureTask o Better left for another session ● To make matters worse, AsyncTask has some issues as well.
  • 15. Issues with AsyncTask ● Run the same app, but this time, rotate the screen while the task is going.! ● In order to prevent that, we need to either o Lock screen orientation (at least while in task) o Use Fragments ● Of course we’re going to use Fragments. Who asked that question?
  • 16. Stage 5 ● Create a dummy (blank) Fragment with no UI, but our AsyncTask ● Make sure to call setRetainInstance(true); ● Use a local variable to re-initiate the progress dialogs if needed.
  • 17. Handler ● A Handler can be used to receive messages from other threads ● The handler resides in the UI thread and updates the UI components accordingly
  • 18. Stage 6 ● Use the usual Activity with a new Thread ● Run the Thread and pass a message to a Handler in the Activity
  • 20. is here https://github.com/tdevinda/DialogAndroidIntro_3 Check branches asynctask and handler (you will need git) Final Code