Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

Android Concurrency &

Synchronization: Part 6

Douglas C. Schmidt
d.schmidt@vanderbilt.edu
www.dre.vanderbilt.edu/~schmidt

Institute for Software


Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA

CS 282 Principles of Operating Systems II


Systems Programming for Android
Android Concurrency & Synchronization D. C. Schmidt

Learning Objectives in this Part of the Module


• Understand Android concurrency Message Background
idioms & associated programming
Queue Thread A

mechanisms
Handler

Message

Message Runnable

Looper
Message Handler

Message
Background
Message Thread B

Message
Message
Async
UI Thread Task
(main thread)

2
Android Concurrency & Synchronization D. C. Schmidt

Motivating Android Concurrency Idioms


• Android’s UI has several design
constraints
• An “Application Not Responding”
(ANR) dialog is generated if app’s
UI Thread doesn’t respond to user
input within a short time

See developer.android.com/training/articles/perf-anr.html
3 for more on ANRs
Android Concurrency & Synchronization D. C. Schmidt

Motivating Android Concurrency Idioms


• Android’s UI has several design
constraints
• An “Application Not Responding”
(ANR) dialog is generated if app’s
UI Thread doesn’t respond to user
input within a short time
• Non-UI Threads can’t access
widgets in the UI toolkit since
it’s not thread-safe

android-developers.blogspot.com/2009/05/painless-threading.html
4 has more
Android Concurrency & Synchronization D. C. Schmidt

Motivating Android Concurrency Idioms


• Android’s UI has several design Message
Queue
constraints
• Android therefore supports various
concurrency idioms for processing
long-running operations in background
thread(s) & communicating with the
UI Thread Message

Looper
Message

Message

Message

Message
Message

UI Thread
(main thread)

See developer.android.com/training/multiple-threads/communicate-ui.html
5
Android Concurrency & Synchronization D. C. Schmidt

Motivating Android Concurrency Idioms


• Android’s UI has several design Message Background
Queue
constraints Thread A

• Android therefore supports various Handler


concurrency idioms for processing
long-running operations in background Message
thread(s) & communicating with the
UI Thread Message Runnable

Looper
• Handlers, Messages, & Message Handler
Runnables
Message
• Allows an app to spawn threads Background
Thread B
that perform background Message

operations & publish results Message


on the UI thread Message

UI Thread
(main thread)

www.vogella.com/articles/AndroidBackgroundProcessing/article.html
6 has more
Android Concurrency & Synchronization D. C. Schmidt

Motivating Android Concurrency Idioms


• Android’s UI has several design Message Background
Queue
constraints Thread A

• Android therefore supports various Handler


concurrency idioms for processing
long-running operations in background Message
thread(s) & communicating with the
UI Thread Message Runnable

Looper
• Handlers, Messages, & Message Handler
Runnables
Message
• AsyncTask Background
Message Thread B
• Allow an app to run background
operations & publish results Message
on the UI thread without Message
manipulating threads or Async
handlers UI Thread
(main thread)
Task

www.vogella.com/articles/AndroidBackgroundProcessing/article.html
7 has more
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


Message
• A Looper provides a message Queue
queue to a thread
• Only one Looper is allowed
per Thread

Message

Looper
Message

Message

Message
The UI Thread has a
Looper, but Loopers Message
can also be used in Message
non-UI threads
Thread

8
developer.android.com/reference/android/os/Looper.html has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message public class Looper {
queue to a thread ...
final MessageQueue mQueue;
• Only one Looper is allowed
per Thread public static void loop() {
• The Looper.loop() method runs ...
a Thread’s main event loop, which
waits for Messages & dispatches for (;;) {
them to their Handlers Message msg =
queue.next();
...

msg.target.
dispatchMessage(msg);
...
}
...

9
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message public class Looper {
queue to a thread ...
final MessageQueue mQueue;
• Only one Looper is allowed
per Thread public static void loop() {
• The Looper.loop() method runs ...
a Thread’s main event loop, which
waits for Messages & dispatches for (;;) {
them to their Handlers Message msg =
queue.next();
...

This call can block msg.target.


dispatchMessage(msg);
...
}
...

10
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message public class Looper {
queue to a thread ...
final MessageQueue mQueue;
• Only one Looper is allowed
per Thread public static void loop() {
• The Looper.loop() method runs ...
a Thread’s main event loop, which
waits for Messages & dispatches for (;;) {
them to their Handlers Message msg =
queue.next();
...

msg.target.
dispatchMessage(msg);
...
}
Note inversion of control ...

11
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message public class Looper {
queue to a thread ...
• Only one Looper is allowed
public void prepare() {
per Thread ...
• The Looper.loop() method runs }
a Thread’s main event loop, which
waits for Messages & dispatches public static void loop() {
them to their Handlers ...
}

public void quit() {


...
}

...

frameworks/base/core/java/android/os/Looper.java
12 has the source code
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message public class Thread
queue to a thread implements Runnable {
public static Thread
• By default Threads don’t have
currentThread() {
a message loop associated with ...
them }

public final void join() {


...
}

public void interrupt() {


...
}

public synchronized void start() {


...
}

developer.android.com/reference/java/lang/Thread.html
13 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class LooperThread extends Thread
queue to a thread {
public Handler mHandler;
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• To create one, call
mHandler = new Handler() {
• prepare() in the thread that
public void handleMessage
is to run the loop & then (Message msg) {
// process incoming msgs
}};

Looper.loop();
}

developer.android.com/reference/android/os/Looper.html
14 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class LooperThread extends Thread
queue to a thread {
public Handler mHandler;
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• To create one, call
mHandler = new Handler() {
• prepare() in the thread that
public void handleMessage
is to run the loop & then (Message msg) {
• Create Handlers to process // process incoming msgs
incoming messages (need }};
not go here)
Looper.loop();
}

developer.android.com/reference/android/os/Looper.html
15 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class LooperThread extends Thread
queue to a thread {
public Handler mHandler;
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• To create one, call
mHandler = new Handler() {
• prepare() in the thread that
public void handleMessage
is to run the loop & then (Message msg) {
• Create Handlers to process // process incoming msgs
incoming messages (need }};
not go here)
Looper.loop();
• loop() to have it process }
messages until the loop is
stopped

developer.android.com/reference/android/os/Looper.html
16 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class HandlerThread extends Thread {
queue to a thread Looper mLooper;
...
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• HandlerThread is a helper class synchronized (this) {
for starting a new Thread that mLooper = Looper.myLooper();
automatically contains a Looper ...
}
...
Note the use of the onLooperPrepared();
Template Method Looper.loop();
pattern to handle fixed ...
steps in the algorithm
protected void onLooperPrepared() {
}
}

17
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class HandlerThread extends Thread {
queue to a thread Looper mLooper;
...
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• HandlerThread is a helper class synchronized (this) {
for starting a new Thread that mLooper = Looper.myLooper();
automatically contains a Looper ...
}
...
onLooperPrepared();
This hook method Looper.loop();
enables subclasses ...
to create Handlers
protected void onLooperPrepared() {
}
}

18
developer.android.com/reference/android/os/HandlerThread.html has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Looper Class


• A Looper provides a message class HandlerThread extends Thread {
queue to a thread Looper mLooper;
...
• By default Threads don’t have
a message loop associated with public void run() {
them Looper.prepare();
• HandlerThread is a helper class synchronized (this) {
for starting a new Thread that mLooper = Looper.myLooper();
automatically contains a Looper ...
}
• The start() method must still ...
be called by client code to onLooperPrepared();
launch the thread Looper.loop();
...

protected void onLooperPrepared() {


}
}

19
frameworks/base/core/java/android/os/HandlerThread.java has the source code
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


Message
• Most interaction with a message Queue
loop is through Handlers
• A Handler allows sending & Handler
processing of Message &
Runnable objects associated Message

with a Thread's MessageQueue


Message Runnable

Looper
Message Handler

Message

Message These Handlers


Message
are associated
with this Thread
Message

Thread1

20
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


Message
• Most interaction with a message Queue
Thread2

loop is through Handlers


• A Handler allows sending & Handler
processing of Message &
Runnable objects associated Message

with a Thread's MessageQueue


Message Runnable

Looper
• Other Threads can communicate
by exchanging Messages & Message Handler
Runnables via a Thread’s Message
Handler(s)
Message Thread3

Message
Message

Thread1

developer.android.com/reference/android/os/Handler.html
21 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message public class Handler {
loop is through Handlers ...
public void handleMessage
• Each Handler object is associated (Message msg) {
with a single Thread & that }
Thread's MessageQueue Subclasses must override this hook
method to process messages

22
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message public class Handler {
loop is through Handlers ...
public void handleMessage
• Each Handler object is associated (Message msg) {
with a single Thread & that }
Thread's MessageQueue
• When you create a new Handler, public Handler() {
it is bound to the Looper Thread mLooper = Looper.myLooper();
if (mLooper == null)
(& its MessageQueue) of the
throw new RuntimeException(
Thread where it is created "Can't create handler
inside thread that hasn’t
called Looper.prepare()");
Handler constructor ensures
that the object is used within mQueue = mLooper.mQueue;
an initialized Looper ...

23
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message public class Looper {
loop is through Handlers ...
final MessageQueue mQueue;
• Each Handler object is associated
with a single Thread & that public static void loop() {
Thread's MessageQueue ...
• When you create a new Handler,
it is bound to the Looper Thread for (;;) {
(& its MessageQueue) of the Message msg =
Thread where it is created queue.next();
...
• From that point on, it will deliver
Messages and Runnables to that msg.target.
Looper Thread’s MessageQueue & dispatchMessage(msg);
execute them as they come out of ...
the queue }
...

24
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message Thread2
loop is through Handlers
• Each Handler object is associated 1. Handler.sendMessage(msg)

with a single Thread & that


Handler
Thread's MessageQueue
• Capabilities of a Handler Message

• Sends Messages & posts


Runnable
Runnables to a Thread
• Thread’s MessageQueue Handler
enqueues/schedules them
for future execution 2. Handler.post
(new Runnable(){
public void run()
{ /* … */ }});)

Thread1 Thread3

25
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message Thread2
loop is through Handlers
• Each Handler object is associated 1. Handler.sendMessage(msg)

with a single Thread & that


Handler
Thread's MessageQueue
• Capabilities of a Handler Message

• Sends Messages & posts


Runnable
Runnables to a Thread
• Implements thread-safe Handler
processing for Messages
2. Handler.post
• In current Thread or (new Runnable(){
different Thread public void run()
{ /* … */ }});)
3. handleMessage()

Thread1 Thread3

frameworks/base/core/java/android/os/Handler.java
26 has source code
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message boolean post(Runnable r)
loop is through Handlers • Add Runnable to MessageQueue
• Each Handler object is associated
boolean postAtTime(Runnable r,
with a single Thread & that long uptimeMillis)
Thread's MessageQueue
• Add Runnable to MessageQueue
• Capabilities of a Handler
• Run at a specific time (based on
• Sends Messages & posts SystemClock.upTimeMillis())
Runnables to a Thread
boolean postDelayed(Runnable r,
• Implements thread-safe long delayMillis)
processing for Messages
• Add Runnable to the message queue
• Handler methods associated
• Run after specified amount of time
with Runnables elapses

developer.android.com/reference/android/os/Handler.html
27 has more info
Android Concurrency & Synchronization D. C. Schmidt

The Android Handler Class


• Most interaction with a message boolean sendMessage(Message msg)
loop is through Handlers • Puts msg at end of queue immediately
• Each Handler object is associated
boolean sendMessageAtFrontOfQueue
with a single Thread & that (Message msg)
Thread's MessageQueue
• Puts msg at front of queue immediately
• Capabilities of a Handler
• Sends Messages & posts boolean sendMessageAtTime
(Message msg, long uptimeMillis)
Runnables to a Thread
• Puts msg on queue at stated time
• Implements thread-safe
processing for Messages boolean sendMessageDelayed
• Handler methods associated (Message msg, long delayMillis)
with Runnables • Puts msg after delay time has passed
• Handler methods associated
with Messages

developer.android.com/reference/android/os/Handler.html
28 has more info
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Android apps have a UI Thread Message
Queue
• The UI Thread is a Looper

Message

Looper
Message

Message

Message

Message
Message

UI Thread
(main thread)

29
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Android apps have a UI Thread Message
Queue
• App components in the same
process use the same UI Thread
• User interaction, system
callbacks, & lifecycle methods
are handled in the UI Thread Message

Looper
Message

Message

Message

Message
Message

UI Thread
(main thread)

30
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Android apps have a UI Thread Message
Queue
• App components in the same
process use the same UI Thread
• Don’t access widgets in the UI
toolkit from non-UI Thread or
block the UI Thread Message

Looper
• Long-running operations should
execute in background Thread(s) Message

Message

Message

Message
Message

UI Thread
(main thread)

31
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Android apps have a UI Thread Message
Queue
Background
Thread A
• App components in the same
process use the same UI Thread Handler
• Don’t access widgets in the UI
toolkit from non-UI Thread or Message

block the UI Thread Message Runnable

Looper
• UI & background threads will
need to communicate via Message Handler

• Sending Messages or posting Message


Background
Runnables to the Looper Message Thread B
Thread’s MessageQueue
Message
Message

UI Thread
(main thread)

32
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Android apps have a UI Thread Message
Queue
Background
Thread A
• App components in the same
process use the same UI Thread Handler
• Don’t access widgets in the UI
toolkit from non-UI Thread or Message

block the UI Thread Message Runnable

Looper
• UI & background threads will
need to communicate via Message Handler

• Sending Messages or posting Message


Background
Runnables to the Looper Message Thread B
Thread’s MessageQueue
• Executing operations in the Message

background using AsyncTask Message


Async
UI Thread Task
(main thread)

33
Android Concurrency &
Synchronization: Part 7

Douglas C. Schmidt
d.schmidt@vanderbilt.edu
www.dre.vanderbilt.edu/~schmidt

Institute for Software


Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA

CS 282 Principles of Operating Systems II


Systems Programming for Android
Android Concurrency & Synchronization D. C. Schmidt

Learning Objectives in this Part of the Module


• Understand how to program with Message Background
the Android concurrency idioms
Queue Thread A

• Handlers & Runnables Handler


• Handlers & Messages
Message
• AsyncTask
Message Runnable

Looper
Message Handler

Message
Background
Message Thread B

Message
Message
Async
UI Thread Task
(main thread)

35
Android Concurrency & Synchronization D. C. Schmidt

Programming with the Handler & Runnables


• Create a Runnable, override its run()
hook method, & pass to a Handler

Runnable

Handler

1. Handler.post
(new Runnable(){
public void run()
{ /* … */ }});)

Background
Thread

UI Thread
(main thread)

36
Android Concurrency & Synchronization D. C. Schmidt

Programming with the Handler & Runnables


• Create a Runnable, override its run()
hook method, & pass to a Handler
• Looper framework calls run()
method in the UI Thread
Runnable

Handler

1. Handler.post
(new Runnable(){
public void run()
{ /* … */ }});)

Background
3. run()
Thread
2. handleMessage()
UI Thread
(main thread)

37
Android Concurrency & Synchronization D. C. Schmidt

Example of Runnables & Handlers


public class SimpleThreadingExample extends Activity {
private ImageView iview;
Create new Handler in UI Thread

private Handler h = new Handler();


public void onCreate(Bundle savedInstanceState) {
... Create/start a new thread
iview = ... when user clicks a button
final Button = ...
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new
LoadIcon(R.drawable.icon)).start();
}
}); Pass the resource
} ID of the icon
...

This code runs38


in the UI Thread
Android Concurrency & Synchronization D. C. Schmidt

Example of Runnables & Handlers


private class LoadIcon implements Runnable {
int resId; Cache resource ID

LoadIconTask(int resId) { this.resId = resId; }

public void run() Convert resource


final Bitmap tmp = ID to bitmap
BitmapFactory.decodeResource(getResources(),
resId);
h.post(new Runnable() {
public void run() {
iview.setImageBitmap(tmp);
}
Create a new Runnable & post it
});
to the UI Thread via the Handler
}
...

This code runs in a39


background thread
Android Concurrency & Synchronization D. C. Schmidt

Posting Runnables on UI thread


public class SimpleThreadingExample extends Activity {
private Bitmap bitmap;
public void onCreate(Bundle savedInstanceState) {
...
final ImageView iview = ...; final Button b = ...;
b.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);}
});
} Create a new Runnable & post it
to the UI Thread via the ImageView
}).start();
...
40
developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)
Android Concurrency & Synchronization D. C. Schmidt

Posting Runnables on UI thread


public class SimpleThreadingExample extends Activity {
private Bitmap bitmap;
public void onCreate(Bundle savedInstanceState) {
...
final ImageView iview = ...; final Button b = ...;
b.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);}
});}
Create a new Runnable & post it
}).start();
to the UI Thread via the Activity

41
developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Android Concurrency & Synchronization D. C. Schmidt

Programming with the Handler & Messages


• Extend the Handler class & Background
Thread
override handleMessage()
hook method 1. Handler h = new Handler() {
public void handleMessage
(Message msg) { ... }

Handler

Message

UI Thread
(main thread)

42
developer.android.com/reference/android/os/Handler.html#handleMessage(android.os.Message)
Android Concurrency & Synchronization D. C. Schmidt

Programming with the Handler & Messages


• Extend the Handler class & Background
Thread
override handleMessage()
2. Message msg =
hook method Handler.obtainMessage
• Create Message & set (SET_PROGRESS_BAR_VISIBILITY,
ProgressBar.VISIBLE);
Message content
• Handler.obtainMessage() Handler

• Message.obtain() Message

• etc.
Message parameters include
• int arg1, arg2
• int what
• Object obj
• Bundle data

UI Thread
(main thread)

43
developer.android.com/reference/android/os/Handler.html#obtainMessage(int, int)
Android Concurrency & Synchronization D. C. Schmidt

Programming with the Handler & Messages


• Extend the Handler class & Background
Thread
override handleMessage()
2. Message msg =
hook method Handler.obtainMessage
• Create Message & set (SET_PROGRESS_BAR_VISIBILITY,
ProgressBar.VISIBLE);
Message content
• Looper framework calls the Handler

handleMessage() method Message


in the UI Thread
3. void handleMessage(Message msg) {
switch (msg.what) {
case SET_PROGRESS_BAR_VISIBILITY: {
progress.setVisibility((Integer)
msg.obj);
break;
}
...

UI Thread
(main thread)

44
Android Concurrency & Synchronization D. C. Schmidt

Example of Messages & Handlers


public class SimpleThreadingExample extends Activity {
...
Called back by Looper
Handler h = new Handler() { framework in UI Thread

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;
}
}
...
45
Android Concurrency & Synchronization D. C. Schmidt

Example of Messages & Handlers


public void onCreate(Bundle savedInstanceState) {
...
iview = …
Create/start a new thread
progress = … when user clicks a button
final Button button = …
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new LoadIcon(R.drawable.icon,
h)).start();
} Pass the resource
ID of the icon
});
}
...

46
Android Concurrency & Synchronization D. C. Schmidt

Example of Messages & Handlers


private class LoadIcon implements Runnable {
public void run() { Send various Messages
Message msg = h.obtainMessage
(SET_PROGRESS_BAR_VISIBILITY, ProgressBar.VISIBLE);
h.sendMessage(msg);
final Bitmap tmp =
BitmapFactory.decodeResource(getResources(), resId);
for (int i = 1; i < 11; i++) {
msg = h.obtainMessage(PROGRESS_UPDATE, i * 10);
h.sendMessageDelayed(msg, i * 100);
}
msg = h.obtainMessage(SET_BITMAP, tmp);
h.sendMessageAtTime(msg, 11 * 200);
msg = h.obtainMessage(SET_PROGRESS_BAR_VISIBILITY,
ProgressBar.INVISIBLE);
h.sendMessageAtTime(msg, 11 * 200);
...

47
Android Concurrency & Synchronization D. C. Schmidt

Programming with AsyncTask


• AsyncTask provides a structured
way to manage work involving
background & UI threads
• Simplifies creation of long-
running tasks that need to
communicate with the UI

Async
Task

UI Thread
(main thread)

developer.android.com/reference/android/os/AsyncTask.html
48 has AsyncTask info
Android Concurrency & Synchronization D. C. Schmidt

Programming with AsyncTask


• AsyncTask provides a structured
way to manage work involving
background & UI threads
• Simplifies creation of long-
running tasks that need to
communicate with the UI
• AsyncTask is designed
as a helper class around
Thread & Handler

Async
Task

UI Thread
(main thread)

frameworks/base/core/java/android/os/AsyncTask.java
49 has the source code
Android Concurrency & Synchronization D. C. Schmidt

Programming with AsyncTask


• AsyncTask provides a structured class LoadIcon extends
way to manage work involving {
AsyncTask<Integer,Integer,Bitmap>

background & UI threads protected Bitmap doInBackground


(Integer... resId) {
• Must be subclassed & hook ...
methods overridden }
protected void onProgressUpdate
(Integer... values) {
...
}
protected void onPostExecute
(Bitmap result) {
...
}
...

Async
Task

UI Thread
(main thread)

frameworks/base/core/java/android/os/AsyncTask.java
50 has the source code
Android Concurrency & Synchronization D. C. Schmidt

Example of Android AsyncTask


public class SimpleThreadingExample extends Activity {
ImageView iview;
ProgressBar progress;
public void onCreate(Bundle savedInstanceState) {
...
iview = …
Create/start a new AsyncTask
progress = … when user clicks a button
final Button button = …
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoadIcon().execute(R.drawable.icon);
}
}); Pass the resource
ID of the icon
}
...

52
Android Concurrency & Synchronization D. C. Schmidt

Example of Android AsyncTask


class LoadIcon extends Customize AsyncTask

AsyncTask<Integer, Integer, Bitmap> {


protected void onPreExecute() {
progress.setVisibility(ProgressBar.VISIBLE);
}
Runs before doInBackground()
Runs in background thread in UI Thread

protected Bitmap doInBackground(Integer... resId) {


Bitmap tmp =
BitmapFactory.decodeResource(getResources(),
resId[0]);
publishProgress(...); Convert resource
return tmp; ID to bitmap
} Simulate long-running operation
...

53
Android Concurrency & Synchronization D. C. Schmidt

Example of Android AsyncTask


class LoadIcon extends
AsyncTask<Integer, Integer, Bitmap> {
...
Invoked in response to publishProgress() in UI Thread

protected void onProgressUpdate(Integer... values) {


progress.setProgress(values[0]);
}

protected void onPostExecute(Bitmap result) {


progress.setVisibility(ProgressBar.INVISIBLE);
iview.setImageBitmap(result);
}
... Runs after doInBackground()
in UI Thread

54
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Posting Runnables is simple, but not Message
Queue
particularly flexible

Message Runnable

Looper
Message Handler

Message
Background
Message Thread B

Message
Message

UI Thread
(main thread)

55
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Posting Runnables is simple, but not Message
Queue
Background
particularly flexible Thread A

• Sending Messages is more flexible, Handler


but is more complicated to program
Message

Message Runnable

Looper
Message Handler

Message
Background
Message Thread B

Message
Message

UI Thread
(main thread)

56
Android Concurrency & Synchronization D. C. Schmidt

Summary
• Posting Runnables is simple, but not Message
Queue
Background
particularly flexible Thread A

• Sending Messages is more flexible, Handler


but is more complicated to program
• AsyncTask is powerful, but is more Message

complicated internally & has Message Runnable


more overhead due to potential

Looper
for more thread synchronization Message Handler
& schedulting Message
Background
Message Thread B

Message
Message

UI Thread
(main thread)

57

You might also like