SlideShare a Scribd company logo
1 of 17
Download to read offline
Android	
  Threading	
  
Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciencs	
  
UI	
  Thread	
  
•  When	
  Android	
  app	
  is	
  launched	
  one	
  thread	
  is	
  
created.	
  This	
  thread	
  is	
  called	
  Main	
  Thread	
  or	
  
UI	
  Thread	
  
•  UI	
  Thread	
  is	
  responsible	
  for	
  dispatching	
  events	
  
to	
  widgets	
  
•  Avoid	
  doing	
  0me	
  consuming	
  tasks	
  in	
  UI	
  
Thread	
  since	
  it	
  leads	
  to	
  app	
  that	
  does	
  not	
  
respond	
  quickly	
  
TesAng	
  UI	
  Responsivess	
  
public class ThreadExample extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Do Time Consuming task!");
setContentView(button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
try {
for(int i=0; i<10; i++) {
System.out.println(i);
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Result	
  
TesAng	
  Separate	
  Thread	
  
public class ThreadExample extends Activity implements OnClickListener, Runnable {
...
@Override
public void onClick(View v) {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
try {
for(int i=0; i<10; i++) {
System.out.println(i);
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
How	
  about	
  influencing	
  the	
  UI?	
  
...
@Override
public void run() {
try {
for(int i=0; i<10; i++) {
button.setText("Iteration: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
...
Problem	
  
Why?	
  
•  Android	
  UI	
  Toolkit	
  is	
  not	
  thread	
  safe	
  
•  If	
  you	
  want	
  to	
  manipulate	
  UI,	
  you	
  must	
  do	
  it	
  
inside	
  the	
  UI	
  thread	
  
•  How	
  do	
  you	
  do	
  it	
  then?	
  You	
  can	
  use	
  
– Activity.runOnUiThread(Runnable)
– View.post(Runnable)
– View.postDelayed(Runnable, long)
– …
Activity.runOnUiThread(Runnable)
•  The	
  given	
  acAon	
  (Runnable)	
  is	
  executed	
  
immediately	
  if	
  current	
  thread	
  is	
  UI	
  thread	
  
•  If	
  current	
  thread	
  is	
  NOT	
  UI	
  thread,	
  the	
  acAon	
  
(Runnable)	
  is	
  posted	
  to	
  event	
  queue	
  of	
  the	
  UI	
  
Thread	
  
Example	
  of	
  RunOnUiThread	
  
public class ThreadExample extends Activity implements OnClickListener, Runnable {
...
@Override
public void onClick(View v) {
Thread t = new Thread(this);
t.start();
}
public void run() {
// lengthy operation
try {
Thread.sleep(2000);
} catch (InterruptedException e) { }
runOnUiThread(new Update());
}
class Update implements Runnable {
// This action is posted to event queue
public void run() {
button.setText("Finished!");
}
}
}
View.post(Runnable)
View.postDelayed(Runnable, Long)
•  These	
  methods	
  are	
  of	
  view	
  and	
  are	
  use	
  for	
  
updaAng	
  the	
  view	
  
•  AcAon	
  (Runnable)	
  is	
  placed	
  on	
  Message	
  
Queue	
  
•  Runnable	
  acAon	
  runs	
  on	
  UI	
  Thread	
  
•  postDelayed	
  method	
  for	
  delayed	
  acAon	
  
Using	
  post	
  
private int iteration;
...
@Override
public void run() {
try {
for(int i=0; i<10; i++) {
iteration = i;
button.post(new InfluenceUIThread());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class InfluenceUIThread implements Runnable {
public void run() {
button.setText("Iteration = " + iteration);
}
}
Using	
  Anonymous	
  Inner	
  Classes	
  
@Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
try {
for(int i=0; i<10; i++) {
iteration = i;
button.post(new Runnable() {
public void run() {
button.setText("Iteration = " + iteration);
}
});
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
This	
  can	
  be	
  really	
  
confusing...	
  
AsyncTask
•  Goal:	
  take	
  care	
  thread	
  management	
  for	
  you	
  
•  Use	
  it	
  by	
  subclassing	
  it:	
  class	
  MyTask	
  extends	
  
AsyncTask	
  
•  Override	
  onPreExecute(),	
  onPostExecute()	
  
and	
  onProgressUpdate()
– Invokes	
  in	
  UI	
  Thread	
  
•  Override	
  doInBackground()
– Invokes	
  in	
  worker	
  thread	
  
Example	
  (Google	
  SDK)	
  
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
 new DownloadFilesTask().execute(url1, url2, url3);
Params,	
  Progress,	
  Result	
  
public class ThreadExample extends Activity implements OnClickListener {
private Button button;
...
class MyBackgroundTask extends AsyncTask<Integer, Integer, Integer> {
protected Integer doInBackground(Integer... ints) {
int i = ints[0];
try {
for(i=0; i<10; i++) {
System.out.println("doInBackground!");
publishProgress(new Integer(i));
Thread.sleep(1000);
}
} catch(Exception e) {
e.printStackTrace();
}
return i;
}
protected void onProgressUpdate(Integer iteration) {
button.setText("Iteration = " + iteration);
}
protected void onPostExecute(Integer result) {
button.setText("Finished with result of: " + result);
}
}
}

More Related Content

What's hot

Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-pptSrijib Roy
 
Android notification
Android notificationAndroid notification
Android notificationKrazy Koder
 
Android application structure
Android application structureAndroid application structure
Android application structureAlexey Ustenko
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studioParinita03
 
UI controls in Android
UI controls in Android UI controls in Android
UI controls in Android DivyaKS12
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
Android application development ppt
Android application development pptAndroid application development ppt
Android application development pptGautam Kumar
 
Manipulating Android tasks and back stack
Manipulating Android tasks and back stackManipulating Android tasks and back stack
Manipulating Android tasks and back stackRan Nachmany
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycleSokngim Sa
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMSJussi Pohjolainen
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycleSoham Patel
 

What's hot (20)

Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-ppt
 
Android notification
Android notificationAndroid notification
Android notification
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
Android Components
Android ComponentsAndroid Components
Android Components
 
UI controls in Android
UI controls in Android UI controls in Android
UI controls in Android
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Android Intent.pptx
Android Intent.pptxAndroid Intent.pptx
Android Intent.pptx
 
Android application development ppt
Android application development pptAndroid application development ppt
Android application development ppt
 
Manipulating Android tasks and back stack
Manipulating Android tasks and back stackManipulating Android tasks and back stack
Manipulating Android tasks and back stack
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Android Telephony Manager and SMS
Android Telephony Manager and SMSAndroid Telephony Manager and SMS
Android Telephony Manager and SMS
 
Android intents
Android intentsAndroid intents
Android intents
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
Fragment
Fragment Fragment
Fragment
 

Viewers also liked

Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
 
Android async task
Android async taskAndroid async task
Android async taskMadhu Venkat
 
Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and PublishingJussi Pohjolainen
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android DevelopmentJussi Pohjolainen
 
Android Http Connection and SAX Parsing
Android Http Connection and SAX ParsingAndroid Http Connection and SAX Parsing
Android Http Connection and SAX ParsingJussi Pohjolainen
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs TutorialPerfect APK
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Paris Android User Group
 
Android Wi-Fi Manager and Bluetooth Connection
Android Wi-Fi Manager and Bluetooth ConnectionAndroid Wi-Fi Manager and Bluetooth Connection
Android Wi-Fi Manager and Bluetooth ConnectionJussi Pohjolainen
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkJussi Pohjolainen
 
Thread management
Thread management Thread management
Thread management Ayaan Adeel
 
00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.ppt00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.pptJussi Pohjolainen
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Nehil Jain
 

Viewers also liked (20)

Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Android async task
Android async taskAndroid async task
Android async task
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
 
Qt Translations
Qt TranslationsQt Translations
Qt Translations
 
Android Essential Tools
Android Essential ToolsAndroid Essential Tools
Android Essential Tools
 
Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and Publishing
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Responsive Web Site Design
Responsive Web Site DesignResponsive Web Site Design
Responsive Web Site Design
 
Android Http Connection and SAX Parsing
Android Http Connection and SAX ParsingAndroid Http Connection and SAX Parsing
Android Http Connection and SAX Parsing
 
Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014Deep dive into android restoration - DroidCon Paris 2014
Deep dive into android restoration - DroidCon Paris 2014
 
Android Wi-Fi Manager and Bluetooth Connection
Android Wi-Fi Manager and Bluetooth ConnectionAndroid Wi-Fi Manager and Bluetooth Connection
Android Wi-Fi Manager and Bluetooth Connection
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation Framework
 
Thread management
Thread management Thread management
Thread management
 
00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.ppt00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.ppt
 
Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]Lecture Slides for Preferences and Menus [Android ]
Lecture Slides for Preferences and Menus [Android ]
 
Android service
Android serviceAndroid service
Android service
 
Android UI Development
Android UI DevelopmentAndroid UI Development
Android UI Development
 

Similar to Android Threading

Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Lifeparticle
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Stacy Devino
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VIHari Christian
 
Orsiso
OrsisoOrsiso
Orsisoe27
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"IT Event
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
SenchaCon 2010: Developing components and extensions for ext js
SenchaCon 2010: Developing components and extensions for ext jsSenchaCon 2010: Developing components and extensions for ext js
SenchaCon 2010: Developing components and extensions for ext jsMats Bryntse
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2Paramvir Singh
 

Similar to Android Threading (20)

Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Orsiso
OrsisoOrsiso
Orsiso
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Thread
ThreadThread
Thread
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
9 services
9 services9 services
9 services
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Play image
Play imagePlay image
Play image
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
SenchaCon 2010: Developing components and extensions for ext js
SenchaCon 2010: Developing components and extensions for ext jsSenchaCon 2010: Developing components and extensions for ext js
SenchaCon 2010: Developing components and extensions for ext js
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

Android Threading

  • 1. Android  Threading   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciencs  
  • 2. UI  Thread   •  When  Android  app  is  launched  one  thread  is   created.  This  thread  is  called  Main  Thread  or   UI  Thread   •  UI  Thread  is  responsible  for  dispatching  events   to  widgets   •  Avoid  doing  0me  consuming  tasks  in  UI   Thread  since  it  leads  to  app  that  does  not   respond  quickly  
  • 3. TesAng  UI  Responsivess   public class ThreadExample extends Activity implements OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = new Button(this); button.setText("Do Time Consuming task!"); setContentView(button); button.setOnClickListener(this); } @Override public void onClick(View v) { try { for(int i=0; i<10; i++) { System.out.println(i); Thread.sleep(10000); } } catch (InterruptedException e) { e.printStackTrace(); } } }
  • 5. TesAng  Separate  Thread   public class ThreadExample extends Activity implements OnClickListener, Runnable { ... @Override public void onClick(View v) { Thread thread = new Thread(this); thread.start(); } @Override public void run() { try { for(int i=0; i<10; i++) { System.out.println(i); Thread.sleep(10000); } } catch (InterruptedException e) { e.printStackTrace(); } } }
  • 6.
  • 7. How  about  influencing  the  UI?   ... @Override public void run() { try { for(int i=0; i<10; i++) { button.setText("Iteration: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } ...
  • 9. Why?   •  Android  UI  Toolkit  is  not  thread  safe   •  If  you  want  to  manipulate  UI,  you  must  do  it   inside  the  UI  thread   •  How  do  you  do  it  then?  You  can  use   – Activity.runOnUiThread(Runnable) – View.post(Runnable) – View.postDelayed(Runnable, long) – …
  • 10. Activity.runOnUiThread(Runnable) •  The  given  acAon  (Runnable)  is  executed   immediately  if  current  thread  is  UI  thread   •  If  current  thread  is  NOT  UI  thread,  the  acAon   (Runnable)  is  posted  to  event  queue  of  the  UI   Thread  
  • 11. Example  of  RunOnUiThread   public class ThreadExample extends Activity implements OnClickListener, Runnable { ... @Override public void onClick(View v) { Thread t = new Thread(this); t.start(); } public void run() { // lengthy operation try { Thread.sleep(2000); } catch (InterruptedException e) { } runOnUiThread(new Update()); } class Update implements Runnable { // This action is posted to event queue public void run() { button.setText("Finished!"); } } }
  • 12. View.post(Runnable) View.postDelayed(Runnable, Long) •  These  methods  are  of  view  and  are  use  for   updaAng  the  view   •  AcAon  (Runnable)  is  placed  on  Message   Queue   •  Runnable  acAon  runs  on  UI  Thread   •  postDelayed  method  for  delayed  acAon  
  • 13. Using  post   private int iteration; ... @Override public void run() { try { for(int i=0; i<10; i++) { iteration = i; button.post(new InfluenceUIThread()); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } class InfluenceUIThread implements Runnable { public void run() { button.setText("Iteration = " + iteration); } }
  • 14. Using  Anonymous  Inner  Classes   @Override public void onClick(View v) { new Thread(new Runnable() { public void run() { try { for(int i=0; i<10; i++) { iteration = i; button.post(new Runnable() { public void run() { button.setText("Iteration = " + iteration); } }); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } This  can  be  really   confusing...  
  • 15. AsyncTask •  Goal:  take  care  thread  management  for  you   •  Use  it  by  subclassing  it:  class  MyTask  extends   AsyncTask   •  Override  onPreExecute(),  onPostExecute()   and  onProgressUpdate() – Invokes  in  UI  Thread   •  Override  doInBackground() – Invokes  in  worker  thread  
  • 16. Example  (Google  SDK)   private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {      protected Long doInBackground(URL... urls) {          int count = urls.length;          long totalSize = 0;          for (int i = 0; i < count; i++) {              totalSize += Downloader.downloadFile(urls[i]);              publishProgress((int) ((i / (float) count) * 100));          }          return totalSize;      }      protected void onProgressUpdate(Integer... progress) {          setProgressPercent(progress[0]);      }      protected void onPostExecute(Long result) {          showDialog("Downloaded " + result + " bytes");      }  }  new DownloadFilesTask().execute(url1, url2, url3); Params,  Progress,  Result  
  • 17. public class ThreadExample extends Activity implements OnClickListener { private Button button; ... class MyBackgroundTask extends AsyncTask<Integer, Integer, Integer> { protected Integer doInBackground(Integer... ints) { int i = ints[0]; try { for(i=0; i<10; i++) { System.out.println("doInBackground!"); publishProgress(new Integer(i)); Thread.sleep(1000); } } catch(Exception e) { e.printStackTrace(); } return i; } protected void onProgressUpdate(Integer iteration) { button.setText("Iteration = " + iteration); } protected void onPostExecute(Integer result) { button.setText("Finished with result of: " + result); } } }