Transcript Threads

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 the “main thread”
prohibits UI events from being handled
This means that any long-running code should run
in a background thread
However, background threads are not allowed to
modify UI elements!
How Android threading works



Create a class that extends AsyncTask
To start the new thread, call the AsyncTask's
execute method
When execute is called, Android does the
following:
1. runs onPreExecute in the main (UI) thread
2. runs doInBackground in a background thread
3. runs onPostExecute in the main (UI) thread
Let's add threads to our app!



We want the app to “sleep” for two seconds and then redraw the
random shapes
We will create an inner class called BackgroundDrawingTask that
extends AsyncTask and implement two methods:
–
doInBackground will just sleep for two seconds
–
onPostExecute will call invalidate the DrawableView,
causing the View to be redrawn
We then create a BackgroundDrawingTask and call its execute
method to start the new thread
In the DrawableView class, add line 43
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// this version of onDraw randomly chooses a color
// and position for drawing the rectangles
protected void onDraw(Canvas canvas) {
// this is the “paintbrush”
Paint paint = new Paint();
// loop for each rectangle to draw
for (int i = 0; i < count; i++) {
// set the color randomly
int whichColor = (int)(Math.random() * 4);
if (whichColor == 0) paint.setColor(Color.RED);
else if (whichColor == 1) paint.setColor(Color.GREEN);
else if (whichColor == 2) paint.setColor(Color.BLUE);
else paint.setColor(Color.YELLOW);
// set the position randomly
int x = (int)(Math.random()*200);
int y = (int)(Math.random()*300);
// draw Rectangle
canvas.drawRect(x, y, x+50, y+50, paint);
}
// launch a new background thread
if (count > 0) new BackgroundDrawingTask().execute();
}
Create an inner class in the DrawableView class...
47
class BackgroundDrawingTask extends AsyncTask<Integer,
Void, Integer> {
48
49
// this method gets run in the background
50
protected Integer doInBackground(Integer... args) {
51
try { Thread.sleep(2000); } catch (Exception e) { }
52
return 1;
53
}
54
55
// this method gets run in the UI thread
56
protected void onPostExecute(Integer result) {
57
// cause the DrawableView to get redrawn
58
invalidate();
59
}
60
61 } // end of BackgroundDrawingTask class
62
63 } // end of DrawableView class
Where can you go from here?



Create a game in which the user has to touch on
the randomly-appearing shapes
The shapes change color when they're touched,
and the “score” is tracked
As the user advances, the number of shapes
and/or the frequency with which they are redrawn
can be increased