You are on page 1of 42

13

Android Multi-Threading
Notes are based on:
The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright 2008-2009 CommonsWare, LLC. ISBN: 978-0-9816780-0-9 & Android Developers http://developer.android.com/index.html

13. Android Multi-Threading

Multi-Threading
Threads
http://developer.android.com/reference/java/lang/Thread.html

1.Mi thread l mt n v thc thi song song (concurrent unit of execution). 2.Mi thread c call stack ring cho cc phng thc c gi, cc tham s v bin a phng ca chng. 3.Mi thc th my o (mi my o dnh cho 1 tin trnh mt ng dng ang chy), khi c chy, s c t nht mt thread chnh chy, thng thng c vi thread khc dnh cho cc nhim v phc v thread chnh. 4.ng dng c th bt cc thread b sung phc v cc mc ch c th.

13. Android Multi-Threading

Multi-Threading
Threads
http://developer.android.com/reference/java/lang/Thread.html

Cc thread trong cng mt my o tng tc v ng b ha vi nhau qua vic s dng cc i tng dng chung (shared objects) v cc monitor (module kim sot vic dng chung) gn vi cc i tng ny. C hai cch chnh chy mt thread t trong m ng dng. 1. To mt lp mi extend lp Thread v override phng thc run(). 2. To mt instant mi ca lp Thread vi mt i tng Runnable . Trong c hai cch, cn gi phng thc start() thc s chy Thread mi.

13. Android Multi-Threading

Multi-Threading
Process (tin trnh) 1
(Dalvik Virtual Machine 1)

Process 2 (Dalvik Virtual Machine 2)

Common memory resources (ti nguyn b nh dng chung)

Common memory resources

Main thread Thread-2 Thread-1

main thread

13. Android Multi-Threading

Multi-Threading
Advantages of Multi-Threading
1. Cc thread dng chung ti nguyn ca tin trnh nhng li thc thi c lp. 2. C th tch cc trch nhim ca ng dng main thread chy UI, v cc tc thread chy di nn thc hin cc nhim v tn thi gian. 3. Vic s dng thread l mt tru tng ha hu ch v s thc thi song song (concurrent execution). 4. c bit c ch trong trng hp mt tin trnh n sinh ra nhiu thread chy trn mt h thng multiprocessor. y, ta c x l song song thc s (real parallelism). 5.Kt qu, mt chng trnh a lung s vn hnh nhanh hn trn mt h thng nhiu CPU.
5

13. Android Multi-Threading

Multi-Threading
Disadvantages of Multi-Threading
1. M chng trnh c xu hng phc tp hn 2. Cn pht hin, trnh, v g (gii quyt) deadlock

N N <- N * 1.01

N N <- N a

1. Temp2 : =n 2. Temp2:= temp* 1.01 3. Ghi temp2 vao N

1. Temp := N 2. Temp := temp a;

3. Ghi temp vao N

13. Android Multi-Threading

Multi-Threading
Cch tip cn ca Android i vi cc vic tn thi gian
Mt ng dng c th c mt hot ng tn thi gian, tuy nhin, ta mun UI vn p ng tt i vi cc tng tc ca ngi dng. Android cung cp hai cch x l tnh hung ny: 1. Thc hin thao tc trong mt service background v dng notification thng bo cho ngi dng v bc tip theo 2. Thc hin thao tc trong mt background thread. Cc thread ca Android tng tc vi nhau bng cch s dng (a) cc i tng Handler v (b) post cc i tng Runnable ti view chnh.

13. Android Multi-Threading

Multi-Threading
Handler Class
http://developer.android.com/reference/android/os/Handler.html

Khi mt tin trnh c to cho mt ng dng, main thread ca n c dnh ring chy mt message queue, queue ny qun l cc i tng bc cao ca ng dng (activity, intent receiver, v.v..) v cc ca s m chng to ra. Ta c th to cc thead ph, chng tng tc vi thread chnh ca ng dng qua mt Handler. Khi ta to mt Handler mi, n c gn vi message queue ca thread to ra n t tr i, n s gi cc message v cc runnable ti message queue v thc thi chng khi chng ra khi message queue.

13. Android Multi-Threading

Multi-Threading
Handler Class
http://developer.android.com/reference/android/os/Handler.html

Hai ng dng chnh ca Handler:

(1) xp lch cho cc message v runnable cn c thc thi vo thi im no trong tng tai, v
(2) xp hng mt action cn thc hin ti mt thread khc

10

13. Android Multi-Threading

Multi-Threading
Threads and UI Warning
Background thread khng c tng tc vi giao din ngi dng (UI).

Ch c main thread c truy nhp view ca main activity.


Cc bin class (ton cc) c th c nhn thy v cp nht t trong cc thread

11

13. Android Multi-Threading

Multi-Threading
Handlers MessageQueue
Mi thread ph (secondary thread) cn lin lc vi thread chnh th phi yu cu mt message token bng cch dng phng thc obtainMessage(). Khi ly c token, thread ph c th ghi d liu vo token v gn n vo message queue ca Handler bng cch dng phng thc sendMessage(). Handler dng phng thc handleMessage() lin tc x l cc message mi c gi ti thread chnh. Mi message c ly ra t queue ca thread c th tr v d liu cho thread chnh hoc yu cu chy cc i tng runnable qua phng thc post().

12

13. Android Multi-Threading

Multi-Threading

13

13. Android Multi-Threading

Multi-Threading
Using Messages Main Thread
... Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) {

Background Thread
... Thread backgJob = new Thread (new Runnable (){ @Override public void run() { //...do some busy work here ... //get a token to be added to //the main's message queue Message msg = myHandler.obtainMessage(); ... //deliver message to the //main's message-queue myHandler.sendMessage(msg); }//run });//Thread //this call executes the parallel thread backgroundJob.start(); ...

// do something with the message... v // update GUI if needed! ... }//handleMessage


};//myHandler ...

14

13. Android Multi-Threading

Multi-Threading
Using Post Main Thread Background Thread
... Handler myHandler = new Handler(); // this is the "Runnable" object @Override // that executes the background thread public void onCreate( Bundle savedInstanceState) { private Runnable backgroundTask ... = new Runnable () { Thread myThread1 = @Override new Thread(backgroundTask, public void run() { "backAlias1"); ... Do some background work here myThread1.start(); myHandler.post(foregroundTask); }//onCreate ... //this is the foreground runnable private Runnable foregroundTask = new Runnable() { @Override public void run() { // work on the UI if needed } ... }//run };//backgroundTask

15

13. Android Multi-Threading

Multi-Threading
Messages
gi mt Message cho mt Handler, u tin thread phi must gi obtainMessage() ly i tng Message ra khi kho (pool). C vi dng obtainMessage(), cho php ta ly mt i tng Message rng hoc cc message cha tham s Example // thread 1 produces some local data String localData = Greeting from thread 1; // thread 1 requests a message & adds localData to it Message mgs = myHandler.obtainMessage (1, localData);

16

13. Android Multi-Threading

Multi-Threading
sendMessage Methods
Ta gi message bng cch gi mt trong cc phng thc sendMessage...() chng hn sendMessage() t message vo cui queue sendMessageAtFrontOfQueue() t message vo u queue (ch khng phi cui nh mc nh), nn message ny s c u tin hn tt c cc message khc sendMessageAtTime() t message vo queue vo thi im cho bi tham s, biu din bng millisecond theo uptime ca h thng (SystemClock.uptimeMillis()) sendMessageDelayed() t message vo queue sau mt tr tnh bng milligiy

17

13. Android Multi-Threading

Multi-Threading
Processing Messages
x l cc message m cc background thread gi n, Handler cn ci listener
handleMessage( . . . ) Phng thc ny s c gi cho tng message xut hin trong message queue. Ti , handler c th cp nht UI nu cn. Tuy nhin, n cn lm vic tht nhanh, v cc nhim v UI khc b treo cho n khi Handler thc hin xong.

18

13. Android Multi-Threading

Multi-Threading
Example 1. Progress Bar Using Message Passing
Main thread hin th progress bar widget dng thanh ngang v dng trn cho bin tin trin ca mt thao tc ang chy ti background. D liu ngu nhin c gi t background thread v cc message c hin ti view chnh.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff009999" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Working ...." android:textSize="18sp" android:textStyle="bold" /> <ProgressBar android:id="@+id/progress" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" /> <ProgressBar android:id="@+id/progress2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/TextView02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="returned from thread..." android:textSize="14sp" android:background="#ff0000ff" android:textStyle="bold" android:layout_margin="7px"/> </LinearLayout>

19

13. Android Multi-Threading

Multi-Threading
Example 1. Progress Bar Using Message Passing
// Multi-threading example using message passing package cis493.threads; import java.util.Random; import import import import import import import android.app.Activity; android.os.Bundle; android.os.Handler; android.os.Message; android.view.View; android.widget.ProgressBar; android.widget.TextView;

public class ThreadDemo1ProgressBar extends Activity { ProgressBar bar1; ProgressBar bar2; TextView msgWorking; TextView msgReturned;

boolean isRunning = false; final int MAX_SEC = 60; // (seconds) lifetime for background thread
String strTest = "global value seen by all threads "; int intTest = 0;

20

13. Android Multi-Threading

Multi-Threading
Example 1. Progress Bar Using Message Passing
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { String returnedValue = (String)msg.obj; //do something with the value sent by the background thread here ... msgReturned.setText("returned by background thread: \n\n" + returnedValue); bar1.incrementProgressBy(2); //testing threads termination if (bar1.getProgress() == MAX_SEC){ msgReturned.setText("Done \n back thread has been stopped"); isRunning = false; } if (bar1.getProgress() == bar1.getMax()){ msgWorking.setText("Done"); bar1.setVisibility(View.INVISIBLE); bar2.setVisibility(View.INVISIBLE); bar1.getLayoutParams().height = 0; bar2.getLayoutParams().height = 0; } else { msgWorking.setText("Working..." + bar1.getProgress() ); } } }; //handler 21

13. Android Multi-Threading

Multi-Threading
Example 1. Progress Bar Using Message Passing
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); bar1 = (ProgressBar) findViewById(R.id.progress); bar2 = (ProgressBar) findViewById(R.id.progress2); bar1.setMax(MAX_SEC); bar1.setProgress(0);

msgWorking = (TextView)findViewById(R.id.TextView01); msgReturned = (TextView)findViewById(R.id.TextView02);


strTest += "-01"; // slightly change the global string intTest = 1; }//onCreate

public void onStop() { super.onStop(); isRunning = false; } 22

13. Android Multi-Threading

Multi-Threading
Example 1. Progress Bar Using Message Passing
public void onStart() { super.onStart(); // bar1.setProgress(0); Thread background = new Thread(new Runnable() { public void run() { try { for (int i = 0; i < MAX_SEC && isRunning; i++) { //try a Toast method here (will not work!) //fake busy busy work here Thread.sleep(1000); //one second at a time Random rnd = new Random(); // this is a locally generated value String data = "Thread Value: " + (int) rnd.nextInt(101); //we can see and change (global) class variables data += "\n" + strTest + " " + intTest; intTest++;

//request a message token and put some data in it Message msg = handler.obtainMessage(1, (String)data);
// if thread is still alive send the message if (isRunning) { handler.sendMessage(msg); } } } catch (Throwable t) { // just end the background thread } }//run });//background isRunning = true; background.start(); }//onStart } //class

23

13. Android Multi-Threading

Multi-Threading
Example 2. Using Handler post(...) Method
Ta th cng mt bi ton nh trc (mt cng vic chy chm ti background v mt UI p ng tt ti foreground), nhng ln ny dng c ch posting chy cc runnable ti foreground

24

13. Android Multi-Threading

Multi-Threading
Example2. Using Handler post(...) Method
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff009999" android:orientation="vertical" xmlns:android=http://schemas.android.com/apk/res/android > <TextView android:id="@+id/lblTopCaption" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="2px" android:text="Some important data is being collected now. Patience please..." android:textSize="16sp" android:textStyle="bold" /> <ProgressBar android:id="@+id/myBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/txtBox1" android:layout_width="fill_parent" android:layout_height="78px" android:layout_marginLeft="20px" android:layout_marginRight="20px" android:textSize="18sp" android:layout_marginTop="10px" /> <Button android:id="@+id/btnDoSomething" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="4px" android:layout_marginLeft="20px" android:text="Do Something" /> </LinearLayout>

25

13. Android Multi-Threading

Multi-Threading
Example2. Using Handler post(...) Method
// using Handler post(...) method to execute foreground runnables package cis493.threads; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class ThreadsPosting extends Activity { ProgressBar TextView EditText Button int long String myBar; lblTopCaption; txtBox1; btnDoSomething; accum = 0; startingMills = System.currentTimeMillis(); PATIENCE = "Some important data is being collected now. " + "\nPlease be patient. ; 26

13. Android Multi-Threading

Multi-Threading
Example2. Using Handler post(...) Method
Handler myHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lblTopCaption = (TextView)findViewById(R.id.lblTopCaption); myBar = (ProgressBar) findViewById(R.id.myBar); myBar.setMax(100);

txtBox1 = (EditText) findViewById(R.id.txtBox1); txtBox1.setHint("Foreground distraction. Enter some data here");


btnDoSomething = (Button)findViewById(R.id.btnDoSomething); btnDoSomething.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Editable txt = txtBox1.getText(); Toast.makeText(getBaseContext(), "You said >> " + txt, 1).show(); }//onClick });//setOnClickListener }//onCreate 27

13. Android Multi-Threading

Multi-Threading
Example2. Using Handler post(...) Method
@Override protected void onStart() { super.onStart(); // create background thread were the busy work will be done Thread myThread1 = new Thread(backgroundTask, "backAlias1" ); myThread1.start(); myBar.incrementProgressBy(0); } // this is the foreground "Runnable" object responsible for GUI updates private Runnable foregroundTask = new Runnable() { @Override public void run() { try { int progressStep = 5; lblTopCaption.setText(PATIENCE + "\nTotal sec. so far: " + (System.currentTimeMillis() - startingMills) / 1000 ); myBar.incrementProgressBy(progressStep); accum += progressStep; if (accum >= myBar.getMax()){ lblTopCaption.setText("Background work is OVER!"); myBar.setVisibility(View.INVISIBLE); } } catch (Exception e) { e.printStackTrace(); } }//run }; //foregroundTask

28

13. Android Multi-Threading

Multi-Threading
Example2. Using Handler post(...) Method
//this is the "Runnable" object that executes the background thread private Runnable backgroundTask = new Runnable () { @Override public void run() { //busy work goes here... try { for (int n=0; n < 20; n++) { //this simulates 1 sec. of busy activity Thread.sleep(1000); //now talk to the main thread myHandler.post(foregroundTask); } } catch (InterruptedException e) { Log.e("<<ERROR>>", e.getMessage() ); } }//run };//backgroundTask

}//ThreadsPosting

29

13. Android Multi-Threading

Thread States
Thread.State BLOCKED Description is blocked and waiting for a lock.

NEW
RUNNABLE TIMED_WAITING WAITING TERMINATED

has been created, but has never been started.


may be run. is waiting for a specified amount of time. is waiting. has been terminated.

30

31

13. Android Multi-Threading

Multi-Threading
Using the AsyncTask class
1. AsyncTask cho php s dng UI thread mt cch d dng v ng cch. 2. AsyncTask cho php thc hin cc hot ng background v gi kt qu cho UI thread m khng phi thao tc vi thread v/hoc handler. 3. Mt tc v khng ng b (asynchronous task) l mt nhim v tnh ton chy ti mt background thread v kt qu s c gi cho UI thread. 4. Mt asynchronous task c nh ngha bi: 3 kiu tng qut (generic) Params, Progress, Result 4 trng thi chnh onPreExecute, doInBackground, onProgressUpdate onPostExecute. 1 phng thc b tr publishProgress

32

13. Android Multi-Threading

Multi-Threading
Using the AsyncTask class
private class VerySlowTask extends AsyncTask<String, Long, Void> {

// Begin - can use UI thread here protected void onPreExecute() {


} // this is the SLOW background thread taking care of heavy tasks // cannot directly change UI protected Void doInBackground(final String... args) { ... publishProgress((Long) someLongValue); } // periodic updates - it is OK to change UI @Override protected void onProgressUpdate(Long... value) { } // End - can use UI thread here protected void onPostExecute(final Void unused) { } }
33

13. Android Multi-Threading

Multi-Threading
AsyncTask <Params, Progress, Result> Cc tham s kiu ca AsyncTask Params: kiu d liu ca cc tham s s c gi cho task khi n c thc thi. Progress: kiu ca cc progress unit c cng b trong qu trnh tnh ton ti background (bao nhiu lu th thng bo kt qu tin mt ln). Result: kiu ca kt qu tnh ton ca background.

Khng phi asynchronous task no cng dng n c ba kiu d liu. i vi kiu khng dng n, ta dng kiu Void Lu : C php String c ngha (Varargs) mng gm cc gi tr String, tng t String*+
34

13. Android Multi-Threading

Multi-Threading
AsyncTask's methods onPreExecute(), c gi ti UI thread ngay trc khi tc v (task) c thc thi. Bc ny thng dng setup tc v, chng hn hin mt progress bar ti giao din ngi dng.

doInBackground(Params...), c gi cho background thread ngay sau khi onPreExecute() chy xong. Bc ny thc hin cc tnh ton background m c th tn thi gian. Cc tham s ca asynchronous task c truyn cho bc ny. Kt qu tnh ton phi c tr v bi bc ny v s c truyn li cho bc cui cng. Bc ny cn c th dng publishProgress(Progress...) bo co mt hoc vi n v tin . Cc gi tr ny c cng b ti UI thread, trong bc onProgressUpdate(Progress...).
onProgressUpdate(Progress...), c gi cho UI thread sau mi li gi n publishProgress(Progress...). Thi im thc thi khng xc nh. Phng thc ny c dng hin th mt hnh thc tin ty ti giao din ngi dng. V d, n c th l mt progress bar hoc hin nht trnh (log) ti mt text field.

onPostExecute(Result), c gi cho UI thread sau khi cng vic tnh ton ti background xong. Kt qu tnh ton ca background c truyn cho bc ny qua tham s (Result).
35

13. Android Multi-Threading

Multi-Threading
Example: Using the AsyncTask class

Main task gi mt AsyncTask lm mt cng vic tn thi gian. Cc phng thc AsyncTask thc hin cng vic c yu cu v nh k cp nht UI chnh. Trong v d ny, hot ng ti background ng gp vo ni dung ca text box v iu khin progress bar dng trn.
36

13. Android Multi-Threading

Multi-Threading
Example: Using the AsyncTask class
public class Main extends Activity { Button btnSlowWork; Button btnQuickWork; EditText etMsg; Long startingMillis; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); etMsg = (EditText) findViewById(R.id.EditText01);

btnSlowWork = (Button) findViewById(R.id.Button01); // delete all data from database (when delete button is clicked) this.btnSlowWork.setOnClickListener(new OnClickListener() { public void onClick(final View v) { new VerySlowTask().execute(); } });
btnQuickWork = (Button) findViewById(R.id.Button02); // delete all data from database (when delete button is clicked) this.btnQuickWork.setOnClickListener(new OnClickListener() { public void onClick(final View v) { etMsg.setText((new Date()).toLocaleString()); } }); }// onCreate

37

13. Android Multi-Threading

Multi-Threading
Example: Using the AsyncTask class
private class VerySlowTask extends AsyncTask <String, Long, Void> { private final ProgressDialog dialog = new ProgressDialog(Main.this); // can use UI thread here protected void onPreExecute() { startingMillis = System.currentTimeMillis(); etMsg.setText("Start Time: " + startingMillis); this.dialog.setMessage("Wait\nSome SLOW job is being done..."); this.dialog.show(); } // automatically done on worker thread (separate from UI thread) protected Void doInBackground(final String... args) { try { // simulate here the slow activity for (Long i = 0L; i < 3L; i++) { Thread.sleep(2000); publishProgress((Long)i); } } catch (InterruptedException e) { Log.v("slow-job being done", e.getMessage()) } return null; }

38

13. Android Multi-Threading

Multi-Threading
Example: Using the AsyncTask class
// periodic updates - it is OK to change UI @Override protected void onProgressUpdate(Long... value) { super.onProgressUpdate(value); etMsg.append("\nworking..." + value[0]); } // can use UI thread here protected void onPostExecute(final Void unused) { if (this.dialog.isShowing()) { this.dialog.dismiss(); } // cleaning-up all done etMsg.append("\nEnd Time:" + (System.currentTimeMillis()-startingMillis)/1000); etMsg.append("\ndone!"); }

}//AsyncTask

}// Main

39

13. Android Multi-Threading

Multi-Threading
Example: Using the AsyncTask class
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="7px" /> <Button android:text="Do some SLOW work" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="7px" /> <Button android:text="Do some QUICK work" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="7px" /> </LinearLayout> 40

13. Android Multi-Threading

Multi-Threading

Questions

41

Bi tp
Vit mt ng dng dng multi-threading lm vic sau: S d ti khon t ng nh k tng thm 15% (li nhp gc) v c hin th trn mn hnh Nu ngi dng nhp s tin ri bm nt Rt hoc Gi th s tin s c tng/gim tng ng. Gi : s tin l bin ca activity c cc thread dng chung.
dng mt thead nh k tnh li v nhp gc UI thread dng cc listener cho cc Button x l event bm nt Rt/Gi
S d ti khon

100.000

10.000 Rt Gi

You might also like