SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Downloaden Sie, um offline zu lesen
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);
}
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycleSoham Patel
 
Android activities & views
Android activities & viewsAndroid activities & views
Android activities & viewsma-polimi
 
android activity
android activityandroid activity
android activityDeepa Rani
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferencesAjay Panchal
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in androidPrawesh Shrestha
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycleSokngim Sa
 
Layouts in android
Layouts in androidLayouts in android
Layouts in androidDurai S
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and responseSahil Agarwal
 
android content providers
android content providersandroid content providers
android content providersDeepa Rani
 

Was ist angesagt? (20)

Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
Android activities & views
Android activities & viewsAndroid activities & views
Android activities & views
 
android activity
android activityandroid activity
android activity
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Android intents
Android intentsAndroid intents
Android intents
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
 
Fragment
Fragment Fragment
Fragment
 
05 intent
05 intent05 intent
05 intent
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Activity lifecycle
Activity lifecycleActivity lifecycle
Activity lifecycle
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
android content providers
android content providersandroid content providers
android content providers
 
Share preference
Share preferenceShare preference
Share preference
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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] 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
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] 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
 

Ähnlich wie 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] 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
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Kürzlich hochgeladen (20)

SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

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