0% found this document useful (0 votes)
63 views83 pages

AsyncTask pt1

The document discusses the AsyncTask framework in Android for performing background operations and publishing results on the UI thread without manipulating threads directly. It notes that AsyncTask classes are strongly connected, allowing tasks to run concurrently through facades that simplify access to complex frameworks. The AsyncTask class contains public methods that are invoked by apps to execute tasks in background threads or executor pools, as well as lifecycle methods like doInBackground() that are overridden by subclasses to perform work.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views83 pages

AsyncTask pt1

The document discusses the AsyncTask framework in Android for performing background operations and publishing results on the UI thread without manipulating threads directly. It notes that AsyncTask classes are strongly connected, allowing tasks to run concurrently through facades that simplify access to complex frameworks. The AsyncTask class contains public methods that are invoked by apps to execute tasks in background threads or executor pools, as well as lifecycle methods like doInBackground() that are overridden by subclasses to perform work.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Android Concurrency:

The AsyncTask Framework

Douglas C. Schmidt

[email protected]
www.dre.vanderbilt.edu/~schmidt
Institute for Software
Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA

Learning Objectives in this Part of the Module


Recognize the concurrency idioms & mechanisms associated with
programming the Android AsyncTask framework
Message
Queue

4. doInBackGround()

Looper

FutureTask

Executor

Message
Message
Message

5. onProgressUpdate()
6. onPostExecute()
3. execute(future)

Message
Message
Message
UI Thread

2. onPreExecute()
Handler

AsyncTask

1. execute(url)

(main thread)

Allows apps to perform background operations & publish results on UI


2
handlers, messages, or runnables
thread without manipulating threads,

Overview of the
AsyncTask Framework

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected

Background
Thread A

Message
Queue

Message
Handler

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

See previous part on


the HaMeR4 framework

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases

Message
Queue

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases

Message
Queue

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases

Message
Queue

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases
However, there are drawbacks

Background
Thread A

Message
Queue

Message
Handler

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases
However, there are drawbacks
Must understand patterns

Background
Thread A

Message
Queue

Message
Handler

Looper

Handler
Message
Runnable
Message
Message

Background
Thread B

Message
Message
Message
UI Thread
(main thread)

See en.wikipedia.org/wiki/Active_object &


9
www.dre.vanderbilt.edu/~schmidt/CommandProcessor.pdf

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
This flexibility works well for
simple concurrency use cases
However, there are drawbacks
Must understand patterns
Tedious & error-prone

Background
Thread A

Message
Queue

Message
Handler

Looper

Handler
Message
Runnable
Message
Message
Message
Message
Message
UI Thread
(main thread)

10

Background
Thread B

Overview of the AsyncTask Framework


Background
Thread A

Message
Queue

Message
Handler
handleMessage()

Handler
Looper

Classes in HaMeR framework


are loosely connected
This flexibility works well for
simple concurrency use cases
However, there are drawbacks
Must understand patterns
Tedious & error-prone

Message
Runnable
Message
Message
Message
Message

Message
UI Thread
(main thread)

e.g., apps must understand how to


11
manage the lifecycle
of Messages

Background
Thread B

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

See en.wikipedia.org/wiki/
12
Template_Method_pattern

FutureTask

Looper

Message
Queue

Handler

Executor
AsyncTask

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

13

FutureTask

Looper

Message
Queue

Handler

Executor
AsyncTask

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

14

FutureTask

Looper

Message
Queue

Handler

Executor
AsyncTask

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected
Run concurrently, without directly
manipulating Threads, Handlers,
Messages, or Runnables

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

15

FutureTask

Looper

Message
Queue

Handler

Executor
AsyncTask

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected
Run concurrently, without directly
manipulating Threads, Handlers,
Messages, or Runnables
Smaller surface area

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

16

FutureTask

Looper

Message
Queue

Handler

Executor
AsyncTask

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected
Run concurrently, without directly
manipulating Threads, Handlers,
Messages, or Runnables
Smaller surface area
Complex framework details
accessed via Faade pattern
AsyncTask
1. execute(url)

See en.wikipedia.org/
17
wiki/Facade_pattern

Overview of the AsyncTask Framework


Classes in HaMeR framework
are loosely connected
Classes in AsyncTask framework
are strongly connected
Run concurrently, without directly
manipulating Threads, Handlers,
Messages, or Runnables
Smaller surface area
Complex framework details
accessed via Faade pattern
Wraps complicated subsystem or
framework with simpler interface

4. doInBackGround()
FutureTask

Executor

5. onProgressUpdate()
6. onPostExecute()
3. execute(future)
Handler

2. onPreExecute()

AsyncTask
1. execute(url)

18

Categories of Methods
in AsyncTask

19

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods

See developer.android.com/
20
reference/android/os/AsyncTask.html

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Invoked by apps

AsyncTask<Params, Progress, Result>


execute(Params... params)
Executes the task with the specified
parameters
AsyncTask<Params, Progress, Result>
executeOnExecutor(Executor exec,
Params... params)
Executes the task with the specified
parameters on the specified Executor
static void execute(Runnable
runnable)
Convenience version of execute(Object)
for use with a simple Runnable object
boolean cancel
(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task
...
21

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Invoked by apps

AsyncTask<Params, Progress, Result>


execute(Params... params)
Executes the task with the specified
parameters
AsyncTask<Params, Progress, Result>
executeOnExecutor(Executor exec,
Params... params)
Executes the task with the specified
parameters on the specified Executor
static void execute(Runnable
runnable)
Convenience version of execute(Object)
for use with a simple Runnable object
boolean cancel
(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task
...

execute() runs each AsyncTask one-at-a-time


22
(serially) in a background
thread within a process

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Invoked by apps

AsyncTask<Params, Progress, Result>


execute(Params... params)
Executes the task with the specified
parameters
AsyncTask<Params, Progress, Result>
executeOnExecutor(Executor exec,
Params... params)
Executes the task with the specified
parameters on the specified Executor
static void execute(Runnable
runnable)
Convenience version of execute(Object)
for use with a simple Runnable object
boolean cancel
(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task
...

executeOnExecutor() can run multiple AsyncTasks


concurrently in a pool of23
threads within a process

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Invoked by apps

AsyncTask<Params, Progress, Result>


execute(Params... params)
Executes the task with the specified
parameters
AsyncTask<Params, Progress, Result>
executeOnExecutor(Executor exec,
Params... params)
Executes the task with the specified
parameters on the specified Executor
static void execute(Runnable
runnable)
Convenience version of execute(Object)
for use with a simple Runnable object
boolean cancel
(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task
...
24

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Invoked by apps

AsyncTask<Params, Progress, Result>


execute(Params... params)
Executes the task with the specified
parameters
AsyncTask<Params, Progress, Result>
executeOnExecutor(Executor exec,
Params... params)
Executes the task with the specified
parameters on the specified Executor
static void execute(Runnable
runnable)
Convenience version of execute(Object)
for use with a simple Runnable object
boolean cancel
(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task
...

cancel() requires cooperation by


the AsyncTask, 25
i.e., its voluntary

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Protected hook methods

void onPreExecute()
Runs on UI thread before doInBackground()
abstract Result doInBackground
(Params... params)
Override this method to perform a
computation on a background thread
void onPostExecute(Result result)
Runs on UI thread after doInBackground()
void onProgressUpdate(Progress...
values)
Runs on UI thread after publishProgress()
called
void onCancelled()
Runs on UI thread after cancel() is invoked &
doInBackground() has finished
...

26

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Protected hook methods
Overridden by apps

void onPreExecute()
Runs on UI thread before doInBackground()
abstract Result doInBackground
(Params... params)
Override this method to perform a
computation on a background thread
void onPostExecute(Result result)
Runs on UI thread after doInBackground()
void onProgressUpdate(Progress...
values)
Runs on UI thread after publishProgress()
called
void onCancelled()
Runs on UI thread after cancel() is invoked &
doInBackground() has finished
...

27

Categories of Methods in the AsyncTask Class


The AsyncTask class has two
types of methods
Public methods
Protected hook methods
Overridden by apps
Invoked by framework
At different points of
time &
In different threading
contexts

void onPreExecute()
Runs on UI thread before doInBackground()
abstract Result doInBackground
(Params... params)
Override this method to perform a
computation on a background thread
void onPostExecute(Result result)
Runs on UI thread after doInBackground()
void onProgressUpdate(Progress...
values)
Runs on UI thread after publishProgress()
called
void onCancelled(Result result)
Runs on UI thread after cancel() is invoked &
doInBackground() has finished
...

28

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

29

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

30

Can only be called once


per instance of AsyncTask
by code in the UI Thread

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Implemented as a
variant of the Template
Method pattern

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

See en.wikipedia.org/wiki/
31
Template_method_pattern

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Invoked by framework in
the UI Thread to perform
initialization actions

32

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Invoked by framework in a
background Thread to perform
long duration operations

See www.androiddesignpatterns.com/
33
2014/01/thread-scheduling-in-android.html

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Invoked by framework in UI
Thread when background
Thread calls publishProgress()

34

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Invoked by framework in UI Thread when


doInBackground() returns its result

35

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

36

Called by application
to attempt to stop the
execution of the task

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Invoked by framework in UI
Thread after cancel() is called &
doInBackground() is finished

If onCancelled() is called then


37
onPostExecute()
is not called

Categories of Methods in the AsyncTask Class


AsyncTask must be extended
& one or more of its hook
methods overridden

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

Can periodically call


isCancelled() to check
if its been cancelled

Similar to using Java Thread interrupt


38
requests to voluntarily
shutdown Threads

Categories of Methods in the AsyncTask Class


AsyncTask is also parameterized
by three types used by its
hook methods

Params, Progress, Result

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
P aram s Type used in
onCancelled()

background work
P rogress Type used
when indicating progress
R esult Type of result

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

39

Categories of Methods in the AsyncTask Class


AsyncTask is also parameterized
by three types used by its
hook methods

Params, Progress, Result

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
P aram s Type used in
onCancelled()

background work
P rogress Type used
when indicating progress
R esult Type of result

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

40

Categories of Methods in the AsyncTask Class


AsyncTask is also parameterized
by three types used by its
hook methods

Params, Progress, Result

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
P aram s Type used in
onCancelled()

background work
P rogress Type used
when indicating progress
R esult Type of result

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

41

Categories of Methods in the AsyncTask Class


AsyncTask is also parameterized
by three types used by its
hook methods

Params, Progress, Result

AsyncTask
execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
P aram s Type used in
onCancelled()

background work
P rogress Type used
when indicating progress
R esult Type of result

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

42

Categories of Methods in the AsyncTask Class


Apps must customize the
AsyncTask class to meet
their concurrency needs

class DownloadTask extends


AsyncTask<Uri, Integer, Long> {
protected Long doInBackground
(Uri... urls)
{ /* Download files */ }
protected void onProgressUpdate
(Integer... progress)
{ setProgressPercent(progress[0]); }
protected void onPostExecute
(Long result)
{ showDialog("Downloaded "
+ result
+ " bytes"); }
}
new DownloadTask().execute(downloadURL);

43

Categories of Methods in the AsyncTask Class


Apps must customize the
AsyncTask class to meet
their concurrency needs

class DownloadTask extends


AsyncTask<Uri, Integer, Long> {
protected Long doInBackground
(Uri... urls)
{ /* Download files */ }
protected void onProgressUpdate
(Integer... progress)
{ setProgressPercent(progress[0]); }
protected void onPostExecute
(Long result)
{ showDialog("Downloaded "
+ result
+ " bytes"); }
}
new DownloadTask().execute(downloadURL);

44

Categories of Methods in the AsyncTask Class


Apps must customize the
AsyncTask class to meet
their concurrency needs

class DownloadTask extends


AsyncTask<Uri, Integer, Long> {
protected Long doInBackground
(Uri... urls)
{ /* Download files */ }
protected void onProgressUpdate
(Integer... progress)
{ setProgressPercent(progress[0]); }
protected void onPostExecute
(Long result)
{ showDialog("Downloaded "
+ result
+ " bytes"); }
}
new DownloadTask().execute(downloadURL);

45

Categories of Methods in the AsyncTask Class


Apps must customize the
AsyncTask class to meet
their concurrency needs

class DownloadTask extends


AsyncTask<Uri, Integer, Long> {
protected Long doInBackground
(Uri... urls)
{ /* Download files */ }
protected void onProgressUpdate
(Integer... progress)
{ setProgressPercent(progress[0]); }
protected void onPostExecute
(Long result)
{ showDialog("Downloaded "
+ result
+ " bytes"); }
}
new DownloadTask().execute(downloadURL);

See developer.android.com/
46
reference/android/os/AsyncTask.html

Programming
with AsyncTask

47

Run Async Behavior for SimpleImageDownloads


Downloads & Displays image via AsyncTask

See github.com/douglascraigschmidt/POSA48
15/tree/master/ex/SimpleImageDownloads

Run Async Behavior for SimpleImageDownloads

49

Run Async Behavior for SimpleImageDownloads

50

Run Async Behavior for SimpleImageDownloads


<Button
...
android:onClick="runAsyncTask"
android:text="@string/runAsync" />

51

Run Async Behavior for SimpleImageDownloads


<Button
...
android:onClick="runAsyncTask"
android:text="@string/runAsync" />

public class ImageDownloadsActivity


extends Activity {
...
public void runAsyncTask(View view) {
/* all magic happens here! */
}

See ThreadedDownloads/src/edu/vuum/
52
mocca/ImageDownloadsActivity.java

Run Async Behavior for SimpleImageDownloads


<Button
...
android:onClick="runAsyncTask"
android:text="@string/runAsync" />

public class ImageDownloadsActivity


extends Activity {
...
public void runAsyncTask(View view) {
/* all magic happens here! */
}

53

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

54

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

55

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message

downloading via AsyncTask

Message
Message
Message
Message
UI Thread
(main thread)

56

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

57

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

58

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue

Background
Thread A
Handler

Looper

Message
Message

Runnable

Message

Handler

Message
Message
Message
Message
UI Thread
(main thread)

59

Background
Thread B

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

See en.wikipedia.org/wiki/
60
Template_method_pattern

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

Run Async Behavior for SimpleImageDownloads


Message
Queue
doInBackground()
onPostExecute()

Message
Message
Message
Message
Message

Message
UI Thread
(main thread)

61

FutureTask

Looper

execute()
Handler

Executor
AsyncTask

AsyncTask
Usage
Considerations

62

AsyncTask Usage Considerations


Threads to communicate

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

63

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

64

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

65

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

66

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

67

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate
Unlike HaMeR framework,
no direct manipulation
of Handlers, Messages,
Runnables, or Threads

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

68

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate
It embodies key framework
characteristics

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

2. onPreExecute()

Handler

AsyncTask
Message
UI Thread

1. execute(url)

(main thread)

See earlier discussions on Android of


69
Concurrency Patterns
& Frameworks

AsyncTask Usage Considerations


Threads to communicate
It embodies key framework
characteristics, e.g.
Inversion of control

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

70

1. execute(url)

AsyncTask Usage Considerations


Threads to communicate
It embodies key framework
characteristics, e.g.
Inversion of control
Domain-specific
structure & functionality

Message
Queue

FutureTask

AsyncTask allows UI & background


4. doInBackGround()

Looper

Executor

Message
Message

5. onProgressUpdate()
6. onPostExecute()

Message

3. execute(future)

Message
Message

Handler

2. onPreExecute()
AsyncTask

Message
UI Thread
(main thread)

71

1. execute(url)

AsyncTask Usage Considerations


AsyncTask allows UI & background

AsyncTask

Threads to communicate
It embodies key framework
characteristics, e.g.
Inversion of control
Domain-specific
structure & functionality
Semi-complete portions
of apps

execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

72

AsyncTask Usage Considerations


AsyncTask allows UI & background

AsyncTask

Threads to communicate
It embodies key framework
characteristics, e.g.
Inversion of control
Domain-specific
structure & functionality
Semi-complete portions
of apps

execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

73

AsyncTask Usage Considerations


AsyncTask allows UI & background

AsyncTask

Threads to communicate
It embodies key framework
characteristics, e.g.
Inversion of control
Domain-specific
structure & functionality
Semi-complete portions
of apps

execute()
cancel()
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

ImageDownloadTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
onCancelled()

74

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls

See bon-app-etit.blogspot.com/2013/
75
04/the-dark-side-of-asynctask.html

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Cancellation is voluntary, just
like Thread.interrupt()

Do
Disturb
76

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Dependency on Activity
Memory leaks occur if theres a strong
references to enclosing Activity

77

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Dependency on Activity
Losing results if/when runtime
configurations change
e.g., Activity associated with an
AsyncTask may be destroyed

78

AsyncTask Usage Considerations


AsyncTask allows UI & background Before API 1.6 (Donut):

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Dependency on Activity
Losing results if/when runtime
configurations change
Portability
Concurrency semantics of
AsyncTask execute() have
changed over time

In the first version of AsyncTask, the tasks


were executed serially, so a task won't start
before a previous task is finished. This caused
quite some performance problems. One task
had to wait on another one to finish.

API 1.6 to API 2.3 (Gingerbread):

The Android developers team decided to


change this so that AsyncTasks could run
parallel on a separate worker thread. There
was one problem. Many developers relied on
the sequential behavior and suddenly they
were having a lot of concurrency issues.

API 3.0 (Honeycomb) until now

"Hmmm, developers don't seem to get it? Let's


just switch it back." The AsyncTasks where
executed serially again. However, they can run
parallel via executeOnExecutor(Executor).

79

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Dependency on Activity
Losing results if/when runtime
configurations change
Portability

The Model-View Presenter (MVP)


80
pattern addresses some
of these issues

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
Cancellation
Dependency on Activity
Losing results if/when runtime
configurations change
Portability

run()

executeOnExecutor()

2.offer()

runnable
runnable

WorkerThreads

runnable

1.executeOnExecutor()
Thread
(main thread)

runnable

3.take()
4.run()

WorkQueue

runnable

ThreadPoolExecutor

AsyncTask

Other issues can be addressed by


81
understanding Android
patterns & APIs

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
AsyncTask used throughout Android
frameworks/base/core/java/android/content/AsyncTaskLoader.java
frameworks/base/core/java/android/content/CursorLoader.java
frameworks/base/core/java/android/os/AsyncTask.java
packages/apps/Browser/src/com/android/browser/UrlHandler.java
packages/apps/Calendar/src/com/android/calendar/CalendarController.java
packages/apps/Gallery/src/com/android/camera/ReverseGeocoderTask.java
packages/apps/Nfc/src/com/android/nfc/NfcService.java
packages/apps/Mms/src/com/android/mms/transaction/PushReceiver.java
packages/apps/Phone/src/com/android/phone/CallLogAsync.java
packages/apps/VideoEditor/src/com/android/videoeditor/BaseAdapterWithImages.java
...

82

AsyncTask Usage Considerations


AsyncTask allows UI & background

Threads to communicate
It embodies key framework
characteristics
AsyncTask has traps & pitfalls
AsyncTask used throughout Android
onProgressUpdate() is not widely used

frameworks/base/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
frameworks/base/packages/SystemUI/src/com/android/systemui/recent/
RecentTasksLoader.java
packages/apps/Email/emailcommon/src/com/android/emailcommon/utility/
EmailAsyncTask.java
packages/apps/Email/src/com/android/email/activity/setup/
AccountCheckSettingsFragment.java
packages/apps/Gallery2/src/com/android/gallery3d/app/ManageCachePage.java
packages/apps/Gallery2/src/com/android/gallery3d/ui/ImportCompleteListener.java
packages/apps/Gallery2/src/com/android/gallery3d/ui/MenuExecutor.java
packages/apps/Settings/src/com/android/settings/TrustedCredentialsSettings.java
83

You might also like