8/12/2019 Threads, Part II
1/18
Android ProgrammingLecture 20:
Threads, Part II
11/16/2011
8/12/2019 Threads, Part II
2/18
Handler ExampleIn this example, GUI thread
doesnt count button is responsive;
I can trigger interleaved counting
threads
8/12/2019 Threads, Part II
3/18
Other Uses of Handler
Handler also
supports a
postDelayed(
Runnable runnable,
long delayInMillis)
method Allows delay
before executes
Shuttle bus app reads bus id and delay from
saved SharedPreferences, then starts a loop
(below) of updates at the designated rate
loops by spawning itself again
8/12/2019 Threads, Part II
4/18
CityApp Example
In the CityApp, it seems reasonable that we could pushthe network (web service) and parsing componentsinto a separate thread
Should make GUI much more responsive
However, for the CityApp, once the network query hasbeen started, we dont necessarily need to do anythingelse as a user
It would be nice to have some feedback about progressthough Repeated use ofpostmethod in Handler - Fetching data, Parsing
data, messages????
8/12/2019 Threads, Part II
5/18
Runnables Runnable as used in the example are pretty static
we cant parameterize them in meaningful ways
Could arguably create classes that implementRunnable interface, and the classes could beparameterized
On next slide, I take the Runnables from a fewslides back that updated the GUI with
Start/Done messages and make themparameterized so that I can write any message
8/12/2019 Threads, Part II
6/18
Parameterized Runnable Example
Before After
8/12/2019 Threads, Part II
7/18
AsyncTask
Android supports a fairly simple mechanismthat simplifies/hides the process of working
directly with threads, theAsyncTaskclass
(asynchronous task)
One extends the AsyncTask class and
implements several methods
doInBackground do the actual work (required)
onProgressUpdate report progress (optional)
onPostExecute report results (optional)
onPreExecute initialize (optional)
8/12/2019 Threads, Part II
8/18
AsyncTasks
Put your seatbelt on
AsyncTasks are conceptually straight-forward,
but syntactically challenging
Well start with an example and think of itconceptually
8/12/2019 Threads, Part II
9/18
Using AsyncTask
Lets lookat an
example:
counting
to ten
million
again
8/12/2019 Threads, Part II
10/18
Varargs
AsyncTask makes use of varargs variablenumber of arguments to a function
C/C++ printf:
printf(Hello!);
printf(Hello %d, x);printf(Hello %d %d, x, y)
Same function, takes arbitrary number ofparameters as final argument
8/12/2019 Threads, Part II
11/18
VarargsIn Java, write function header as follows:
void f(type parameter)
{ code }
meaning functionfcan take an arbitrary number ofparameters of type type (but only that type, whichis different from C/C++)
Can be passed as a comma separated seriesof values or as an array
Only allowed for last parameter
8/12/2019 Threads, Part II
12/18
AsyncTask
Remember: One extends the AsyncTask classand implements several methods
doInBackground do the actual work (required)
onProgressUpdate report progress (optional) onPostExecute report results (optional)
onPreExecute initialize (optional)
8/12/2019 Threads, Part II
13/18
AsyncTask In defining class, use extends AsyncTaskproviding as comma separated
class parametersthe following in this order: Single class type of input parameter(s) to be used in doInBackground
function
Single class type used to report progress Usually Integer
Single class type used as result value from task, which must match returnvalue type from doInBackground
If your function doesnt need parameters, indicate a type of Void (notVoid)
class MyTask extends AsyncTask means canuse String parameters for doInBackgroundand progress andcompletion reporting will use ints (Integer class)
Write AsyncTask extension as an inner class of Activity class so has
access to Activity GUI components
8/12/2019 Threads, Part II
14/18
Implementing AsyncTask
Writeprotected ReturnTypedoInBackground(ParameterType params)
Not thread-safe (dont change GUI directly)
Must return a value of ReturnType
Can process parameters using an array or iteration
Array:
for (j = 0; j < params.length; j++) { do work }
Iteration:
for (String x: params) { }
If want to update progress, callpublishProgress
method with appropriate arguments
Android passes this off to your onProgressUpdate method
8/12/2019 Threads, Part II
15/18
Implementing AsyncTask
Writeprotected void onProgressUpdate(Typeprogress)
Is thread-safe (can change GUI directly)
Update progress bar???
Writeprotected void onPostExecute(Type
result)
Is thread-safe (can change GUI directly)
8/12/2019 Threads, Part II
16/18
Using AsyncTask
Declare and construct an instance of yourAsyncTask subclass
Call the executemethod on that instance, sending
in a comma separated list of values of the type
that doInBackgroundtakes as parameters
If no parameters to be sent, use (Void[]) null
A few last rules:
The task must be allocated, and executed on the mainGUI thread
Any allocated task can only be run once
Internal methods should not be called directly
8/12/2019 Threads, Part II
17/18
Using AsyncTask
Lets lookat an
example:
counting
to ten
million
again
8/12/2019 Threads, Part II
18/18
Using AsyncTask with Progress Updates
Added onProgressUpdate method and
publishProgress callMultiple counting tasks
executing (2nd, 3rdinterleaved)