Multithreading in Android

Post on 23-Feb-2016

62 views 0 download

Tags:

description

Multithreading in Android. Alaa M. Alsalehi Software Engineer at IUG. Agenda. Multithreading vocabulary Main thread in android Time-consuming & blocking operations Unresponsive program Thread safety in android Message Passing is the solution Timer & Timer Task AsyncTask. - PowerPoint PPT Presentation

Transcript of Multithreading in Android

ALAA M. ALSALEHISOFTWARE ENGINEER AT IUG

Multithreading in Android

Agenda

Multithreading vocabularyMain thread in androidTime-consuming & blocking operationsUnresponsive programThread safety in androidMessage Passing is the solutionTimer & Timer TaskAsyncTask

Multithreading vocabulary

Thread vs. processMultithreadingSynchronizationThread safeLock Design PatternMessage Passing PatternVolatileSwing multithreadingSwing utilitySwing worker

Main thread

All Android application components run on the main application thread Activities, Services, and Broadcast Receivers

Time-consumingBlocking operation In any component

will block all other components including Services and the visible Activity

Time-consuming & blocking operations

File operationsNetwork lookupsDatabase transactionsComplex calculationsetc

Unresponsive program

Android OS save himself from application does not response for input events.

Unresponsive programActivities

within 5 secondsBroadcast Receivers

onReceive handlers within 10 seconds.

Unresponsive Exception

Solution

Create your own threadprivate void doLongOperationInThread() { (new Thread(new Runnable() {

public void run() { String result = doLongOperation();

} })).start();

}

What about update UI from other thread?

private void doLongOperationInThread() { (new Thread(new Runnable() {

public void run() { String result = doLongOperation(); updateUI(result);

} })).start();

}

Thread safety in android

Exception

FATAL EXCEPTION: Thread-10 android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

at android.view.ViewRoot.checkThread(ViewRoot.java:2932) at android.view.ViewRoot.invalidateChild(ViewRoot.java:642) at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668) at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511) at android.view.View.invalidate(View.java:5279) at android.widget.TextView.checkForRelayout(TextView.java:5507) at android.widget.TextView.setText(TextView.java:2724) at android.widget.TextView.setText(TextView.java:2592) at android.widget.TextView.setText(TextView.java:2567) at

com.modonat.threadNeed.ThreadNeedActivity.updateUI(ThreadNeedActivity.java:46) at

com.modonat.threadNeed.ThreadNeedActivity.access$2(ThreadNeedActivity.java:44) at com.modonat.threadNeed.ThreadNeedActivity$2.run(ThreadNeedActivity.java:34) at java.lang.Thread.run(Thread.java:1019)

Is android UI thread-safe?

Unfortunately like swing the answer will be No.

Fortunately android has a good solution for this problem.

Main thread who has control on UI

Other thread who is doing

long/blocking operatiions

Create

Update UI

Message Passing

Android depend on message passing to solve this problem.

Handler

private void updateUIByHandler() { final Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { updateUI((String) msg.obj); }

}; (new Thread(new Runnable() {

public void run() { Message msg = myHandler.obtainMessage();//get message object

msg.obj = doLongOperation(1000);

myHandler.sendMessage(msg);//send message to handle it } })).start(); }

Timer

Like thread like timer in UI update.Timer timer=new Timer();timer.schedule(new TimerTask() {

@Override public void run() {

Message msg = myHandler.obtainMessage(); msg.obj = doLongOperation(1000); myHandler.sendMessage(msg);}

}, 1000);

AsyncTask

onPreExecute is invoked before the execution.

onPostExecute is invoked after the execution.

doInBackground  the main operation. Write your heavy operation here.

onProgressUpdate  Indication to the user on progress. It is invoked every

time publishProgress() is called.

Refrence

Android in Practice by CHARLIE COLLINS, MICHAEL D. GALPIN and MATTHIAS KÄPPLER

Professional Android™ Application Development by Reto Meier

Article “Android – Multithreading in a UI environment” http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/