SlideShare a Scribd company logo
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);
}
}
}
Ad

More Related Content

What's hot (20)

Notification android
Notification androidNotification android
Notification android
ksheerod shri toshniwal
 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
Betclic Everest Group Tech Team
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
Soham Patel
 
Android Services
Android ServicesAndroid Services
Android Services
Ahsanul Karim
 
Android UI
Android UIAndroid UI
Android UI
nationalmobileapps
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
MaryadelMar85
 
Low Level View of Android System Architecture
Low Level View of Android System ArchitectureLow Level View of Android System Architecture
Low Level View of Android System Architecture
National Cheng Kung University
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
Ajay Panchal
 
Android Preferences
Android PreferencesAndroid Preferences
Android Preferences
Rashad Aliyev
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Action Bar in Android
Action Bar in AndroidAction Bar in Android
Action Bar in Android
Prof. Erwin Globio
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
Rehan Choudhary
 
Android intents
Android intentsAndroid intents
Android intents
Siva Ramakrishna kv
 
Introduction to flutter
Introduction to flutter Introduction to flutter
Introduction to flutter
Wan Muzaffar Wan Hashim
 
Alarms
AlarmsAlarms
Alarms
maamir farooq
 
Android studio installation
Android studio installationAndroid studio installation
Android studio installation
PoojaBele1
 
Shared preferences
Shared preferencesShared preferences
Shared preferences
Sourabh Sahu
 
Android: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast ReceiversAndroid: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast Receivers
CodeAndroid
 

Viewers also liked (20)

Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Diego Grancini
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
Jussi Pohjolainen
 
Qt Translations
Qt TranslationsQt Translations
Qt Translations
Jussi Pohjolainen
 
Android Essential Tools
Android Essential ToolsAndroid Essential Tools
Android Essential Tools
Jussi Pohjolainen
 
Android Security, Signing and Publishing
Android Security, Signing and PublishingAndroid Security, Signing and Publishing
Android Security, Signing and Publishing
Jussi Pohjolainen
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
Jussi Pohjolainen
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
Jussi Pohjolainen
 
Responsive Web Site Design
Responsive Web Site DesignResponsive Web Site Design
Responsive Web Site Design
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 Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
Perfect APK
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh 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 2014
Paris 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 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
 
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.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
 
Android service
Android serviceAndroid service
Android service
Kirill Rozov
 
Android UI Development
Android UI DevelopmentAndroid UI Development
Android UI Development
Jussi Pohjolainen
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Diego Grancini
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 
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 Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
Perfect APK
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh 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 2014
Paris 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 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
 
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.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
 
Ad

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)
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
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
dhrubo kayal
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 
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
Hari Christian
 
Orsiso
OrsisoOrsiso
Orsiso
e27
 
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
 
Thread
ThreadThread
Thread
phanleson
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
Iegor Fadieiev
 
Android best practices
Android best practicesAndroid best practices
Android best practices
Jose Manuel Ortega Candel
 
9 services
9 services9 services
9 services
Ajayvorar
 
Gwt.create
Gwt.createGwt.create
Gwt.create
Mauricio (Salaboy) Salatino
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
Play image
Play imagePlay image
Play image
Fardian Syah
 
[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
KatyShimizu
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
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
Mats Bryntse
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
Duong Thanh
 
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 VI
Hari Christian
 
Orsiso
OrsisoOrsiso
Orsiso
e27
 
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. .pptx
creativegamerz00
 
[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
KatyShimizu
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
KatyShimizu
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
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
Mats Bryntse
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
Duong Thanh
 
Ad

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
Jussi Pohjolainen
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
Jussi Pohjolainen
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
Jussi Pohjolainen
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
Jussi Pohjolainen
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
Jussi 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 Animation
Jussi 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 libGDX
Jussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Jussi Pohjolainen
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
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 Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
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
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
Jussi 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 Animation
Jussi 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 libGDX
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
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
Jussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
Jussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
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
 

Recently uploaded (20)

IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 

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