CS 696 Mobile Phone Application Development
Fall Semester, 2009
Doc 10 Threads
Oct 1, 2009
Copyright ©, All rights reserved. 2009 SDSU & Roger Whitney, 5500
Campanile Drive, San Diego, CA 92182-7700 USA. OpenContent (http://
[Link]/[Link]) license defines the copyright on this
document.
References
The Busy Coder's Guide to Android Development, V2.1, Mark L. Murphy
2
Code Quality
3
Formating & Names
public void cal(){
//[Link]([Link]());
Double billAmount = null;
Double tipPercent = null;
Double totalAmount = null;
if([Link]().toString().length() < 1)
{
clr();
else
{
4
Names
messageText = (EditText) findViewById([Link]);
messageText01 = (EditText) findViewById([Link].EditText01);
messageText02 = (EditText) findViewById([Link].EditText02);
cal = (Button) findViewById([Link]);
clr = (Button) findViewById([Link]);
5
Threads
6
Activity code runs in UI thread
7
Do not interact with Views in your threads
8
Android Background Tools
Java threads Services
Handler
Messages
Runnables
AsyncTask
9
Handler
Attached to thread it is created in
Processes
Message objects
Runnable objects
Main Uses
Schedule messages/runnables to be executed as in the future
Enqueue an action to be performed on a different thread
10
Handler Scheduling
post(Runnable)
postAtTime(Runnable, long)
postDelayed(Runnable, long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message, long)
sendMessageDelayed(Message, long)
11
ProgressBar Example
Just shows a progress bar progressing
12
Example from The Busy Coder's Guide to Android Development, V2.1, Mark L. Murphy
ThreadExample
public class ThreadExample extends Activity {
ProgressBar progressView;
boolean isRunning = false;
Handler handler = new Handler() {
public void handleMessage(Message empty) {
[Link](5);
}
};
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
progressView = (ProgressBar) findViewById([Link]);
}
public void onStop() {
[Link]();
isRunning = false;
}
13
Example from The Busy Coder's Guide to Android Development, V2.1, Mark L. Murphy
ThreadExample
public void onStart() {
[Link]();
[Link](0);
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20 && isRunning; i++) {
[Link](1000);
[Link]([Link]());
}
} catch (Throwable t) {// just end }
}
});
isRunning = true;
[Link]();
}
}
14
Sending Text Messages to the future
Rather than use a thread use
sendMessageDelayed
Sends data in the message using Bundle
15
Sending Text The Hard Way
public class ThreadExample extends Activity {
Handler handler = new Handler() {
public void handleMessage(Message word) {
String text = [Link]().getString("key");
[Link]([Link], text, Toast.LENGTH_SHORT).show();
}
};
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
}
public void onStart() {
[Link]();
String[] text = { "Bat", "cat", "dat", "fat", "hat", "mat" };
for (int i = 0; i < [Link]; i++) {
Bundle data = new Bundle();
[Link]("key", text[i]);
Message word = new Message();
[Link](data);
[Link](word, 1000 * (i + 1));
} 16
Read the documentation to find the easy way
}
Progress Dialog
Displays a Progress Dialog
Uses Message what to transmit data
17
ThreadExample
public class ThreadExample extends Activity {
ProgressDialog waitDialog;
private static final int WAIT_DIALOG_KEY = 0;
Handler handler = new Handler() {
public void handleMessage(Message command) {
if ([Link] == 0)
showDialog(WAIT_DIALOG_KEY);
else
[Link]();
}
};
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
}
18
ThreadExample
protected Dialog onCreateDialog(int id) {
switch (id) {
case WAIT_DIALOG_KEY: {
waitDialog = new ProgressDialog(this);
[Link]("Please wait while loading...");
[Link](true);
[Link](true);
return waitDialog;
}
}
return null;
}
public void onStart() {
[Link]();
Message on = new Message();
[Link] = 0;
[Link](on, 1000);
Message off = new Message();
[Link] = 1;
[Link](off, 8000);
}
}
19
AsyncTask
20
AsyncTask
Replaces threads & Messages
Android 1.5
Subclass AsyncTask
onPreExecute()
Run in UI thread
Done first
doInBackground(Params...)
Run in seperate thread
publishProgress(Progress...)
Call in doInBackground() to register progress
onProgressUpdate(Progress...)
Run in UI thread
Called by publisheProgress
onPostExecute(Result)
Run in UI thread
Run after doInBackground ends
21
Rules
The AsyncTask sublcass instance must be created on the UI thread
execute(Params...)
Starts the task
Must be invoked on the UI thread
Do not call manually
onPreExecute(), onPostExecute(Result), doInBackground(Params...),
onProgressUpdate(Progress...)
The task can be executed only once
22
AsyncTask Types
private class SampleTask extends AsyncTask<Params, Progress, Result>
Params
Type of argument for
doInBackground()
execute()
Progress
Type of argument for
publishProgress()
onProgressUpdate()
Result
Return type for doInBackground()
Type of argument for onPostExecute()
23
How it Works
private class SampleTask extends AsyncTask<Params, Progress, Result>
UI Thread Background Thread
new SampleTask().execute(paramsType);
onPreExecute() doInBackground(Params... stuff){
blah
publishProgress(progressType);
onProgressUpdate(Progress... values)
blah
return x;
}
onPostExecute(Result result)
24
Example
Loops in the background and displays Toast
25
ThreadExample
public class ThreadExample extends Activity {
private class SampleTask extends AsyncTask<String, String, Void> {
protected Void doInBackground(String... words) {
for (String word : words) {
publishProgress(word);
[Link](1000);
}
return (null);
}
protected void onPostExecute(Void unused) {
[Link]([Link], "Done", Toast.LENGTH_SHORT)
.show();
}
26
ThreadExample
protected void onPreExecute() {
[Link]([Link], "Start", Toast.LENGTH_SHORT)
.show();
}
protected void onProgressUpdate(String... word) {
[Link]([Link], word[0], Toast.LENGTH_SHORT)
.show();
}
}
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
}
public void onStart() {
[Link]();
String[] text = { "Bat", "cat", "dat", "fat", "hat", "mat" };
new SampleTask().execute(text);
}
}
27
Just For Fun
Dynamically update
List View
28
The Task
public class ThreadExample extends ListActivity {
private class SampleTask extends AsyncTask<Void, String, Void> {
String[] items = { "Gautama Buddha", "Kalki", "Krishna", "Kurma",
"Matsya", "Narasimha", "Parashurama", "Rama", "Vamana",
"Varaha" };
protected Void doInBackground(Void... notused) {
for (String word : items) {
publishProgress(word);
[Link](2500);
}
return (null);
}
protected void onPostExecute(Void unused) {
[Link]([Link], "Done", Toast.LENGTH_SHORT)
.show();
}
protected void onProgressUpdate(String... word) {
[Link](word[0]);
}
}
29
Based on an example from The Busy Coder's Guide to Android Development, V2.1, Mark L. Murphy
The Activity
private ArrayAdapter<String> listAdapter;
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link]);
listAdapter = new ArrayAdapter<String>(this,
[Link].simple_list_item_1, new ArrayList<String>());
setListAdapter(listAdapter);
new SampleTask().execute();
}
}
30