SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
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);
}
}
}

Más contenido relacionado

La actualidad más candente

android layouts
android layoutsandroid layouts
android layouts
Deepa Rani
 
Android resource
Android resourceAndroid resource
Android resource
Krazy Koder
 
Day: 1 Introduction to Mobile Application Development (in Android)
Day: 1 Introduction to Mobile Application Development (in Android)Day: 1 Introduction to Mobile Application Development (in Android)
Day: 1 Introduction to Mobile Application Development (in Android)
Ahsanul Karim
 

La actualidad más candente (20)

Android UI
Android UIAndroid UI
Android UI
 
android layouts
android layoutsandroid layouts
android layouts
 
Android Programming Basics
Android Programming BasicsAndroid Programming Basics
Android Programming Basics
 
Android resource
Android resourceAndroid resource
Android resource
 
Day: 1 Introduction to Mobile Application Development (in Android)
Day: 1 Introduction to Mobile Application Development (in Android)Day: 1 Introduction to Mobile Application Development (in Android)
Day: 1 Introduction to Mobile Application Development (in Android)
 
Android Widget
Android WidgetAndroid Widget
Android Widget
 
Introduction to Android and Android Studio
Introduction to Android and Android StudioIntroduction to Android and Android Studio
Introduction to Android and Android Studio
 
Top 11 Mobile App Development Frameworks
Top 11 Mobile App Development FrameworksTop 11 Mobile App Development Frameworks
Top 11 Mobile App Development Frameworks
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
 
Fragment
Fragment Fragment
Fragment
 
Json
JsonJson
Json
 
Android application development ppt
Android application development pptAndroid application development ppt
Android application development ppt
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Android: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast ReceiversAndroid: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast Receivers
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
 
Android resources
Android resourcesAndroid resources
Android resources
 
Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-ppt
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development ppt
 

Destacado

Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and Publishing
Jussi Pohjolainen
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
Jussi Pohjolainen
 
Android Http Connection and SAX Parsing
Android Http Connection and SAX ParsingAndroid Http Connection and SAX Parsing
Android Http Connection and SAX Parsing
Jussi Pohjolainen
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh Mankad
 
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
Jussi Pohjolainen
 
Android 2D Drawing and Animation Framework
Android 2D Drawing and Animation FrameworkAndroid 2D Drawing and Animation Framework
Android 2D Drawing and Animation Framework
Jussi Pohjolainen
 
00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.ppt00 introduction-mobile-programming-course.ppt
00 introduction-mobile-programming-course.ppt
Jussi 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
 

Destacado (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 a Android Threading

Orsiso
OrsisoOrsiso
Orsiso
e27
 

Similar a 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
 

Más de Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi 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 Gestures
Jussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi 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 Platform
Jussi Pohjolainen
 

Más de 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
 

Último

Último (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

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