SlideShare a Scribd company logo
2
Most read
9
Most read
12
Most read
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();
}
}
}
Android Threading
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 (20)

PPTX
Event In JavaScript
ShahDhruv21
 
PPT
Node.js Basics
TheCreativedev Blog
 
PDF
Action Bar in Android
Prof. Erwin Globio
 
PPTX
Android Layout.pptx
vishal choudhary
 
PDF
Android notification
Krazy Koder
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPT
Object-oriented concepts
BG Java EE Course
 
PPTX
Android share preferences
Ajay Panchal
 
PPT
Android - Android Intent Types
Vibrant Technologies & Computers
 
PPTX
Android Thread
Charile Tsai
 
PPTX
Fragment
nationalmobileapps
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Web Application
Sameer Poudel
 
PPTX
Notification android
ksheerod shri toshniwal
 
PPT
Java And Multithreading
Shraddha
 
PPT
Advanced java
NA
 
PDF
Android Programming Basics
Eueung Mulyana
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
Java(Polymorphism)
harsh kothari
 
PPTX
Android activity lifecycle
Soham Patel
 
Event In JavaScript
ShahDhruv21
 
Node.js Basics
TheCreativedev Blog
 
Action Bar in Android
Prof. Erwin Globio
 
Android Layout.pptx
vishal choudhary
 
Android notification
Krazy Koder
 
Object-oriented concepts
BG Java EE Course
 
Android share preferences
Ajay Panchal
 
Android - Android Intent Types
Vibrant Technologies & Computers
 
Android Thread
Charile Tsai
 
Java exception handling
BHUVIJAYAVELU
 
Web Application
Sameer Poudel
 
Notification android
ksheerod shri toshniwal
 
Java And Multithreading
Shraddha
 
Advanced java
NA
 
Android Programming Basics
Eueung Mulyana
 
C# Exceptions Handling
sharqiyem
 
Java(Polymorphism)
harsh kothari
 
Android activity lifecycle
Soham Patel
 

Viewers also liked (20)

ODP
Android App Development - 07 Threading
Diego Grancini
 
PPTX
Android async task
Madhu Venkat
 
PDF
Building Web Services
Jussi Pohjolainen
 
PPTX
Qt Translations
Jussi Pohjolainen
 
PDF
Android Essential Tools
Jussi Pohjolainen
 
PDF
Android Security, Signing and Publishing
Jussi Pohjolainen
 
PDF
C# for Java Developers
Jussi Pohjolainen
 
PDF
Quick Intro to Android Development
Jussi Pohjolainen
 
PDF
Responsive Web Site Design
Jussi Pohjolainen
 
PDF
Android Http Connection and SAX Parsing
Jussi Pohjolainen
 
PPTX
Android Dialogs Tutorial
Perfect APK
 
PPTX
Android service, aidl - day 1
Utkarsh Mankad
 
PDF
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
PDF
Android Wi-Fi Manager and Bluetooth Connection
Jussi Pohjolainen
 
PDF
Android 2D Drawing and Animation Framework
Jussi Pohjolainen
 
PPTX
Thread management
Ayaan Adeel
 
PDF
00 introduction-mobile-programming-course.ppt
Jussi Pohjolainen
 
PPT
Lecture Slides for Preferences and Menus [Android ]
Nehil Jain
 
PDF
Android service
Kirill Rozov
 
PDF
Android UI Development
Jussi Pohjolainen
 
Android App Development - 07 Threading
Diego Grancini
 
Android async task
Madhu Venkat
 
Building Web Services
Jussi Pohjolainen
 
Qt Translations
Jussi Pohjolainen
 
Android Essential Tools
Jussi Pohjolainen
 
Android Security, Signing and Publishing
Jussi Pohjolainen
 
C# for Java Developers
Jussi Pohjolainen
 
Quick Intro to Android Development
Jussi Pohjolainen
 
Responsive Web Site Design
Jussi Pohjolainen
 
Android Http Connection and SAX Parsing
Jussi Pohjolainen
 
Android Dialogs Tutorial
Perfect APK
 
Android service, aidl - day 1
Utkarsh Mankad
 
Deep dive into android restoration - DroidCon Paris 2014
Paris Android User Group
 
Android Wi-Fi Manager and Bluetooth Connection
Jussi Pohjolainen
 
Android 2D Drawing and Animation Framework
Jussi Pohjolainen
 
Thread management
Ayaan Adeel
 
00 introduction-mobile-programming-course.ppt
Jussi Pohjolainen
 
Lecture Slides for Preferences and Menus [Android ]
Nehil Jain
 
Android service
Kirill Rozov
 
Android UI Development
Jussi Pohjolainen
 
Ad

Similar to Android Threading (20)

PPT
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
PDF
Android development training programme , Day 3
DHIRAJ PRAVIN
 
PPT
Tech talk
Preeti Patwa
 
PDF
[Android] Multiple Background Threads
Nikmesoft Ltd
 
PPTX
Introduction to Android - Session 3
Tharaka Devinda
 
PPTX
Lecture #2 threading, networking &amp; permissions final version #2
Vitali Pekelis
 
PDF
Internals of AsyncTask
BlrDroid
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Tools and Techniques for Understanding Threading Behavior in Android*
Intel® Software
 
PDF
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
PPTX
Advanced #3 threading
Vitali Pekelis
 
PPTX
Performance #6 threading
Vitali Pekelis
 
PDF
Asynchronous Programming in Android
John Pendexter
 
PDF
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
PDF
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
DOCX
androidSample
Matt Kutschera
 
PPTX
Async task, threads, pools, and executors oh my!
Stacy Devino
 
PDF
Not Quite As Painful Threading
CommonsWare
 
PPTX
Advanced #2 threading
Vitali Pekelis
 
PDF
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
DroidConTLV
 
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Android development training programme , Day 3
DHIRAJ PRAVIN
 
Tech talk
Preeti Patwa
 
[Android] Multiple Background Threads
Nikmesoft Ltd
 
Introduction to Android - Session 3
Tharaka Devinda
 
Lecture #2 threading, networking &amp; permissions final version #2
Vitali Pekelis
 
Internals of AsyncTask
BlrDroid
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Tools and Techniques for Understanding Threading Behavior in Android*
Intel® Software
 
Tools and Techniques for Understanding Threading Behavior in Android
Intel® Software
 
Advanced #3 threading
Vitali Pekelis
 
Performance #6 threading
Vitali Pekelis
 
Asynchronous Programming in Android
John Pendexter
 
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
androidSample
Matt Kutschera
 
Async task, threads, pools, and executors oh my!
Stacy Devino
 
Not Quite As Painful Threading
CommonsWare
 
Advanced #2 threading
Vitali Pekelis
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
DroidConTLV
 
Ad

More from Jussi Pohjolainen (20)

PDF
Moved to Speakerdeck
Jussi Pohjolainen
 
PDF
Java Web Services
Jussi Pohjolainen
 
PDF
Box2D and libGDX
Jussi Pohjolainen
 
PDF
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
PDF
libGDX: Tiled Maps
Jussi Pohjolainen
 
PDF
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
PDF
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
PDF
Advanced JavaScript Development
Jussi Pohjolainen
 
PDF
Introduction to JavaScript
Jussi Pohjolainen
 
PDF
Introduction to AngularJS
Jussi Pohjolainen
 
PDF
libGDX: Scene2D
Jussi Pohjolainen
 
PDF
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
PDF
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
PDF
libGDX: User Input
Jussi Pohjolainen
 
PDF
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
PDF
Building Android games using LibGDX
Jussi Pohjolainen
 
PDF
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
PDF
Creating Games for Asha - platform
Jussi Pohjolainen
 
PDF
Intro to Asha UI
Jussi Pohjolainen
 
PDF
Intro to Java ME and Asha Platform
Jussi Pohjolainen
 
Moved to Speakerdeck
Jussi Pohjolainen
 
Java Web Services
Jussi Pohjolainen
 
Box2D and libGDX
Jussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
libGDX: Tiled Maps
Jussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 
Intro to Building Android Games using libGDX
Jussi Pohjolainen
 
Advanced JavaScript Development
Jussi Pohjolainen
 
Introduction to JavaScript
Jussi Pohjolainen
 
Introduction to AngularJS
Jussi Pohjolainen
 
libGDX: Scene2D
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: User Input
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Jussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Jussi Pohjolainen
 
Intro to Asha UI
Jussi Pohjolainen
 
Intro to Java ME and Asha Platform
Jussi Pohjolainen
 

Recently uploaded (20)

PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
July Patch Tuesday
Ivanti
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 

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(); } } }
  • 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); } } }