Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.

Slides:



Advertisements
Similar presentations
Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
Advertisements

Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
Cosc 5/4730 A little on threads and Messages: Handler class.
HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Working in the Background Radan Ganchev Astea Solutions.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
ALAA M. ALSALEHI SOFTWARE ENGINEER AT IUG Multithreading in Android.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
CMSC 330: Organization of Programming Languages Threads.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
CHAP 14. 프로세스와 스레드. © 2012 생능출판사 All rights reserved 다중 스레딩 하나의 애플리케이션이 동시에 여러 가지 작업을 하 는 것 이들 작업은 스레드 (thread) 라고 불린다.
User Interface Layout Interaction. EventsEvent Handlers/Listeners Interacting with a user.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.
Java Thread Programming
Concurrency in Android
Small talk with the UI thread
Android Multi-Threading
Multi Threading.
Concurrency in Android
Java Concurrency.
Lecture 6: Process, Thread, Task
CS499 – Mobile Application Development
Threads Chate Patanothai.
Threads II IS
Android Programming Lecture 8
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Multithreaded Programming
Android Topics Asynchronous Callsbacks
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
Threads in Java James Brucker.
Multithreading in java.
Using threads for long running tasks.
Lecture 6: Process, Thread, Task
Android Threads Dimitar Ivanov Mobile Applications with Android
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads, AsyncTasks & Handlers

 Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process  Implementation view  Each Thread has a program counter and a stack  The heap and static areas are shared across threads 2

3 CPU 1CPU 2 p3p1p2p4 t1 t2 t3 t4 t5 t6 t7 t8 Computer Processes Threads

 void start() - starts the Thread  boolean isAlive() - returns true if the thread has been started, but hasn’t yet terminated  void interrupt() - send an interrupt request to calling Thread  void join() - wait for a thread to die 4

 void sleep(long time) - sleep for the given period  Thread currentThread() - thread object for currently executing thread  Boolean holdsLock(Object object) - returns true if calling Thread holds an intrinsic lock on object 5

 Instantiate a Thread object  Invoke the Thread’s start() method  Thread will invoke its own run()  Thread terminates when run() returns 6

public class SimpleThreadingExample extends Activity { private Bitmap bitmap; public void onCreate(Bundle savedInstanceState) { … final ImageView iview = … new Thread(new Runnable() { public void run() { synchronized (iview) { bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); iview.notify(); } }).start(); …

final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { synchronized (iview) { while (null == bitmap) { try { iview.wait(); } catch (InterruptedException e) {…} } iview.setImageBitmap(bitmap); } }); …

 Applications have a main thread (the UI thread)  Application components in the same process use the same main thread  User interaction, system callbacks & lifecycle methods handled in the UI thread  UI toolkit is not thread safe

 Blocking the UI thread hurts responsiveness  Long-running ops should run in background thread  Don’t access the UI toolkit from non-UI thread  UI & background threads will need to communicate

public class SimpleThreadingExample extends Activity { private Bitmap bitmap; public void onCreate(Bundle savedInstanceState) { … final ImageView iview = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap = … iview.post(new Runnable() { public void run() { iview.setImageBitmap(bitmap);} }); } }).start(); …

public class SimpleThreadingExample extends Activity { private Bitmap bitmap; public void onCreate(Bundle savedInstanceState) { … final ImageView iview = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap = … SimpleThreadingExample.this.runOnUiThread( new Runnable() { public void run() { iview.setImageBitmap(bitmap);} }); } }).start(); …

 Structured way to manage work involving background &UI threads  In background thread  Perform work  In UI Thread  Setup  Indicate progress  Publish results

 Generic class class AsyncTask { … }  Generic type parameters  Params – Types used in background work  Progress – Types used when indicating progress  Result – Types of result

 void onPreExecute()  Runs before doInBackground()  Result doInBackground (Params... params)  Performs work  Can call void publishProgress(Progress... values)  void onProgressUpdate (Progress... values)  Invoked in response to publishProgress()  void onPostExecute (Result result)  Runs after doInBackground()

public class SimpleThreadingExample extends Activity { ImageView iview; ProgressBar progress; public void onCreate(Bundle savedInstanceState) { … iview = … progress = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new LoadIconTask().execute(R.drawable.icon); } }); } …

class LoadIconTask extends AsyncTask { protected Bitmap doInBackground(Integer... resId) { Bitmap tmp = BitmapFactory.decodeResource( getResources(), resId[ 0 ]); // simulate long-running operation publishProgress(…); return tmp; } protected void onProgressUpdate(Integer... values) { progress.setProgress(values[ 0 ]); } protected void onPostExecute(Bitmap result) { iview.setImageBitmap(result); } …

 Threads can also communicate by exchanging Messages & Runnables  Looper  One per Thread  Manages MessageQueue  Dispatches MessageQueue entries  Handler  Sends Messages & Runnables to Thread  Implements processing for Messages

 Two main uses for a Handler  Schedule Message/Runnable for future execution  Enqueue action to be performed on a different thread

 boolean post(Runnable r)  Add Runnable to the MessageQueue  boolean postAtTime(Runnable r, long uptimeMillis)  Add Runnable to the MessageQueue. Run at a specific time (based on SystemClock.upTimeMillis())  boolean postDelayed(Runnable r, long delayMillis)  Add Runnable to the message queue. Run after the specified amount of time elapses

public class SimpleThreadingExample extends Activity { private ImageView iview; private Handler handler = new Handler(); public void onCreate(Bundle savedInstanceState) { … iview = … final Button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new LoadIconTask(R.drawable.icon)).start(); } }); } …

private class LoadIconTask implements Runnable { int resId; LoadIconTask(int resId) { this.resId = resId; } public void run() { final Bitmap tmp = BitmapFactory.decodeResource(getResources(),resId); handler.post(new Runnable() { public void run() { iview.setImageBitmap(tmp); } }); } …

 Create Message & set Message content  Handler.obtainMessage()  Message.obtain()  Many variants, see documentation  Message parameters include  int arg1, arg2  int what  Object obj  Bundle data

 sendMessage() - puts the Message on the queue immediately  sendMessageAtFrontOfQueue() – puts the Message at the front of the queue immediately  sendMessageAtTime() – puts the message on the queue at the stated time  sendMessageDelayed() – puts the message after the delay time has passed

public class SimpleThreadingExample extends Activity { … Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case SET_PROGRESS_BAR_VISIBILITY: { progress.setVisibility((Integer) msg.obj); break; } case PROGRESS_UPDATE: { progress.setProgress((Integer) msg.obj); break; } case SET_BITMAP: { iview.setImageBitmap((Bitmap) msg.obj); break; } } …

public void onCreate(Bundle savedInstanceState) { … iview = … progress = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread( new LoadIconTask(R.drawable.icon, handler)).start(); } }); } …

private class LoadIconTask implements Runnable { … public void run() { Message msg = handler.obtainMessage ( SET_PROGRESS_BAR_VISIBILITY, ProgressBar.VISIBLE); handler.sendMessage(msg); final Bitmap tmp = BitmapFactory.decodeResource(getResources(),resId); for (int i = 1; i < 11; i++) { msg = handler.obtainMessage(PROGRESS_UPDATE, i * 10); handler.sendMessageDelayed(msg, i * 200); } …

msg = handler.obtainMessage(SET_BITMAP, tmp); handler.sendMessageAtTime(msg, 11 * 200); msg = handler.obtainMessage( SET_PROGRESS_BAR_VISIBILITY, ProgressBar.INVISIBLE); handler.sendMessageAtTime(msg, 11 * 200); }