0% found this document useful (0 votes)
37 views

Multithreading in A UI Environment

The problem in using threads in a UI environment So what will happen if we use a thread for a long running operation? the result in this case is that the application crashes.

Uploaded by

Homer Java
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Multithreading in A UI Environment

The problem in using threads in a UI environment So what will happen if we use a thread for a long running operation? the result in this case is that the application crashes.

Uploaded by

Homer Java
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Everyday Developer

http://www.aviyehuda.com

HOME OPEN SOURCE ANDROID JAVA OTHERS CONTACT ME ABOUT ME

Previous

Next

Android Multithreading in a UI environment


Posted on 20/12/2010

Why do we need multithreading in Android applications? Lets say you want to do a very long operation when the user pushes a button. If you are not using another thread, it will look something like this:
1 ((Button)findViewById(R.id.Button01)).setOnClickListener( 2 new OnClickListener() { 3 4 @Override 5 public void onClick(View v) { 6 int result = doLongOperation(); 7 updateUI(result); 8 } 9 });

What will happen? The UI freezes. This is a really bad UI experience. The program may even crash.

The problem in using threads in a UI environment So what will happen if we use a Thread for a long running operation. Lets try a simple example:
01 ((Button)findViewById(R.id.Button01)).setOnClickListener( 02 new OnClickListener() { 03 04 @Override 05 public void onClick(View v) { 06 07 (new Thread(new Runnable() { 08 09 @Override 10 public void run() { 11 int result = doLongOperation(); 12 updateUI(result);

converted by Web2PDFConvert.com

13 14 15 16

} })).start(); }

The result in this case is that the application crashes.


12-07 16:24:29.089: ERROR/AndroidRuntime(315): FATAL EXCEPTION: Thread-8 12-07 16:24:29.089: ERROR/AndroidRuntime(315): android.view .View Root$CalledFromW rongThreadException: Only the original thread that created a view hierarchy can touch its view s. 12-07 16:24:29.089: ERROR/AndroidRuntime(315): at ...

Clearly the Android OS wont let threads other than the main thread change UI elements. But why? Android UI toolkit, like many other UI environments, is not thread-safe.

The solution A queue of messages. Each message is a job to be handled. Threads can add messages. Only a single thread pulls messages one by one from the queue. The same solution was implemented in swing (Event dispatching thread and SwingUtilities.invokeLater() )

Handler The Handler is the middleman between a new thread and the message queue.

Option 1 Run the new thread and use the handler to send messages for ui changes
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 final Handler myHandler = new Handler(){ @Override public void handleMessage(Message msg) { updateUI((String)msg.obj); } }; (new Thread(new Runnable() { @Override public void run() { Message msg = myHandler.obtainMessage(); msg.obj = doLongOperation(); myHandler.sendMessage(msg); } })).start();

* keep in mind that updating the UI should still be a short operation, since the UI freezes during the updating process. Other possibilities: handler.obtainMessage with parameters handler.sendMessageAtFrontOfQueue() handler.sendMessageAtTime() handler.sendMessageDelayed() handler.sendEmptyMessage()

Option 2 run the new thread and use the handler to post a runnable which updates the GUI.
01 final Handler myHandler = new Handler(); 02 03 (new Thread(new Runnable() { 04 05 @Override 06 public void run() { 07 final String res = doLongOperation(); 08 myHandler.post(new Runnable() {
converted by Web2PDFConvert.com

09 10 11 12 13 14 15 16 17 18

@Override public void run() { updateUI(res); } }); } })).start(); }

Looper If we want to dive a bit deeper into the android mechanism we have to understand what is a Looper. We have talked about the message queue that the main thread pulls messages and runnables from it and executes them. We also said that each handler you create has a reference to this queue. What we havent said yet is that the main thread has a reference to an object named Looper. The Looper gives the Thread the access to the message queue. Only the main thread has executes to the Looper by default. Lets say you would like to create a new thread and you also want to take advantage of the message queue functionality in that thread.
01 (new Thread(new Runnable() { 02 03 @Override 04 public void run() { 05 06 innerHandler = new Handler(); 07 08 Message message = innerHandler.obtainMessage(); 09 innerHandler.dispatchMessage(message); 10 } 11 })).start();

Here we created a new thread which uses the handler to put a message in the messages queue. This will be the result:
12-10 20:41:51.807: ERROR/AndroidRuntime(254): Uncaught handler: thread Thread-8 exiting due to uncaught exception 12-10 20:41:51.817: ERROR/AndroidRuntime(254): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 12-10 20:41:51.817: ERROR/AndroidRuntime(254): at android.os.Handler.(Handler.java:121) 12-10 20:41:51.817: ERROR/AndroidRuntime(254): at ...

converted by Web2PDFConvert.com

The new created thread does not have a Looper with a queue attached to it. Only the UI thread has a Looper. We can however create a Looper for the new thread. In order to do that we need to use 2 functions: Looper.prepare() and Looper.loop().
01 (new Thread(new Runnable() { 02 03 @Override 04 public void run() { 05 06 Looper.prepare(); 07 innerHandler = new Handler(); 08 09 Message message = innerHandler.obtainMessage(); 10 innerHandler.dispatchMessage(message); 11 Looper.loop(); 12 } 13 })).start();

If you use this option, dont forget to use also the quit() function so the Looper will not loop for ever.
1 @Override 2 protected void onDestroy() { 3 innerHandler.getLooper().quit(); 4 super.onDestroy(); 5 }

AsyncTask I have explained to you that a Handler is the new threads way to communicate with the UI thread. If while reading this you were thinking to yourself, isnt there an easier way to do all of that well, you know what?! There is. Android team has created a class called AsyncTask which is in short a thread that can handle UI. Just like in java you extend the class Thread and a SwingWorker in Swing, in Android you extend the class AsyncTask. There is no interface here like Runnable to implement Im afraid.
01 class MyAsyncTask extends AsyncTask<Integer, String, Long> { 02 03 @Override 04 protected Long doInBackground(Integer... params) { 05 06 long start = System.currentTimeMillis(); 07 for (Integer integer : params) { 08 publishProgress("start processing "+integer); 09 doLongOperation(); 10 publishProgress("done processing "+integer); 11 } 12 13 return start - System.currentTimeMillis(); 14 } 15 16 17 18 @Override 19 protected void onProgressUpdate(String... values) { 20 updateUI(values[0]); 21 } 22 23 @Override 24 protected void onPostExecute(Long time) { 25 updateUI("Done with all the operations, it took:" + 26 time + " millisecondes"); 27 } 28 29 @Override 30 protected void onPreExecute() { 31 updateUI("Starting process"); 32 } 33 34 35 public void doLongOperation() { 36 37 try { 38 Thread.sleep(1000); 39 } catch (InterruptedException e) { 40 e.printStackTrace(); 41 } 42 43 } 44 45 }
converted by Web2PDFConvert.com

This is how you start this thread:


1 MyAsyncTask aTask = new MyAsyncTask(); 2 aTask.execute(1, 2, 3, 4, 5);

AsyncTask defines 3 generic types: AsyncTask<{type of the input}, {type of the update unit}, {type of the result}> You dont have to use all of them simply use Void for any of them.

Notice that AsyncTask has 4 operations, which are executed by order. 1. onPreExecute() is invoked before the execution. 2. onPostExecute() - is invoked after the execution. 3. doInBackground() - the main operation. Write your heavy operation here. 4. onProgressUpdate() Indication to the user on progress. It is invoked every time publishProgress() is called. * Notice: doInBackground() is invoked on a background thread where onPreExecute(), onPostExecute() and onProgressUpdate() are invoked on the UI thread since their purpose is to update the UI.

Android developer website also mentions these 4 rules regarding the AsyncTask: The task instance must be created on the UI thread. execute(Params) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params), onProgressUpdate(Progress) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Timer + TimerTask Another option is to use a Timer. Timer is a comfortable way to dispatch a thread in the future, be it once or more. Instead of doing this:
01 Runnable threadTask = new Runnable() { 02 03 @Override 04 public void run() { 05 06 while(true){ 07 try { 08 Thread.sleep(2000); 09 } catch (InterruptedException e) { 10 e.printStackTrace(); 11 } 12 13 doSomething(); 14 } 15 } 16 }; 17 18 (new Thread(threadTask)).start();

do this:
1 2 3 4 5 6 7 8 9 TimerTask timerTask = new TimerTask() { @Override public void run() { doSomething(); } }; Timer timer = new Timer(); timer.schedule(timerTask, 2000,2000);

which is a bit more elegant. Bare in mind, you still have to use Handler if you need to do UI operations.

converted by Web2PDFConvert.com

Download sources:

Download demo project 1 Download demo project 2


5
Tweet 0

Share

Share

Like

This entry was posted in Android and tagged Android, multithreading by Avi. Bookmark the permalink.

23 THOUGHTS ON ANDROID MULTITHREADING IN A UI ENVIRONMENT

P7h on 21/12/2010 at 21:21 said:

Very neatly written and explained. But only gripe is, code could have used better formatting / syntax highlighting JS. Even otherwise, an excellent article.
Reply

Pingback: Android Multithreading in a UI environment : Mike's burogu

arthur on 05/01/2011 at 18:07 said:

What a great article. I have googled for a long time looking for a good explanation of the topic, and this one is the best I found. Thanks!
Reply

Purush on 21/01/2011 at 11:53 said:

Excellent article, Very clear.


Reply

Pepper on 15/03/2011 at 11:28 said:

so great article. Thanks!


Reply

Hom on 13/05/2011 at 09:04 said:

great article..got clear concept..thanks!


Reply

Kiran on 20/05/2011 at 08:50 said:

Good article to clear concepts !!

converted by Web2PDFConvert.com

Reply

karan on 21/06/2011 at 14:12 said:

gooodddddddd
Reply

karan on 21/06/2011 at 14:15 said:

in multi threadind there is only one interface Runnable() ????????????????


Reply

Monish on 25/07/2011 at 11:12 said:

Thanks a lot, very useful


Reply

vipin on 28/07/2011 at 12:58 said:

A very good article for understanding handler, looper, asynctask. I was reading about them for few days but not able to clear doubts. This article helped me a lot. Thanks
Reply

krishna K Mishra on 17/08/2011 at 21:32 said:

Its really a great tutorial on Complete thread handling in android .. Thank you so much for publishing so nice tutorial.
Reply

Richard L. on 10/11/2011 at 22:30 said:

We have been doing programming without threads, with complexe systems and our UI wouldnt freeze I guess there are many ways to create a piece of software, that will still what it is supposed to do. You can use threads or not and achieve the same thing.
Reply

Avi on 10/11/2011 at 22:59 said:

Hi Richard. If you dont need threads thats great. But the question is: what do you mean by complex. Some of the actions require more time than others. If for example, your application reads pictures from the internet, than I am afraid you will have to use threads, this action takes a few seconds. Bear in mind, that the main thread can not be busy for more than 5 seconds, otherwise the OS will pop an alert to the user asking him whether he wishes to close down the application. Thanks for your comment

converted by Web2PDFConvert.com

Reply

Howard on 27/11/2011 at 16:55 said:

The Best!
Reply

Eric on 22/12/2011 at 07:38 said:

Thx, helped alot


Reply

Rui Pedrosa on 06/01/2012 at 12:18 said:

A simple but very useful explanation! thanks!


Reply

Karol on 14/01/2012 at 01:06 said:

Hi All the examples I see so far implement the Runnable object as inner class of the main UI Thread Activity. In my up I dont want to do this because my runnable does more things and it also extend TextView. Basically it is a timer that display minutes and second passed and does other things. I want it to be separate class but it does not work. Can someon post an example that uses runnable that modifies a UI but it is a separate class. Thanks Karol
Reply

neetika on 30/03/2012 at 09:38 said:

Really simple and useful explanation about threading.i was searching like this.thanks
Reply

Shirish on 10/05/2012 at 10:53 said:

Excellent article! Thanks!


Reply

Guest on 05/06/2012 at 23:17 said:

> Notice that AsyncTask has 4 operations, which are executed by order. Shouldnt that order be 1,3,2 ????
Reply

converted by Web2PDFConvert.com

Guest on 05/06/2012 at 23:19 said:

> The task can be executed only once (an exception will be > thrown if a second execution is attempted.) Once per .. ? Per day? Per minute? After the first one finishes you can start another? It says only *ONCE*? So you can NEVER execute this again? NEVER? So if I need this 10 times I have to cut/paste all the code in 10 times????
Reply

Pingback: Techbeast.net - Google Nexus 7 Announced - Techbeast.net

Leave a Reply
Your email address will not be published. Name

Email

Website

Comment

Post Comment

About Me
RSS

Categories
Android bluetooth ClientSide

converted by Web2PDFConvert.com

Clover General GreaseMonkey Hacks hibernate hibernate validator HTML5 HtmlUnit Image Manipulation Java Java Technologies JavaScript Java_Mail JEE/Network Job searching Open Source Pivot projects Pure Java software Trivia

Recent Comments

dd on Android quick tip: use System.arraycopy() Thanks a lot! This spared me the effort of trying for myself. Regards, Daniel
Posted Jul 08, 2012

Thomas on Memory Game Android Application I have successfully customized design. But now I have problem. I have 24 images and game bord 3x4, I need...
Posted Jul 07, 2012

Thomas on Memory Game Android Application Hi, how can I customize layout? I need more space between pictures. Can you help me. Thanks! :-)
Posted Jun 27, 2012

Jason on Connecting to Bluetooth devices with Java I can run the code, but why localDevice always got null? pls help!
Posted Jun 23, 2012

Roy on 4 JavaScript trivia questions that may help you understand the language a bit better Great refreshment
Posted Jun 11, 2012

converted by Web2PDFConvert.com

Malinda on Connecting to Bluetooth devices with Java Thank you!!! this post helped me a lot~!!!
Posted Jun 07, 2012

Guest on Android Multithreading in a UI environment > The task can be executed only once (an exception will be > thrown if a second execution is attempted.) Once...
Posted Jun 05, 2012

Guest on Android Multithreading in a UI environment > Notice that AsyncTask has 4 operations, which are executed by order. Shouldn't that "order" be 1,3,2 ????
Posted Jun 05, 2012

martin on Memory Game Android Application How to judge the game has been successful??
Posted Jun 02, 2012

murat on Memory Game Android Application Can you please send me an e-mail attached with source codes of this game? The one provided by the link...
Posted May 29, 2012

click here on Android development Custom Animation Although I actually like this post, I think there was an spelling error close towards the finish of your third...
Posted May 29, 2012

Neha on Using Hibernate Validator to cover your validation needs I have a customized constraint for cross field validation which is to be applied to my bean at class level....
Posted May 24, 2012

Shirish on Android Multithreading in a UI environment Excellent article! Thanks!


Posted May 10, 2012

Tuan on Memory Game Android Application Thanks you very much, it very helpful
Posted May 10, 2012
converted by Web2PDFConvert.com

laxman on Android Using SQLite DataBase thank u for the nice sqlite database code. please help me remaining functionalities in sqlitedtabse clearly Thanks, Laxman
Posted May 05, 2012

Faizan on Memory Game Android Application Hi, I really like your game it helps me understand the code within android. Just wanted to know if there is...
Posted Apr 27, 2012

melek on Memory Game Android Application bana bunu kodlarn rarlayp yollarmsn dogru bir ekilde proje devim iin lazm da
Posted Apr 17, 2012

neetika on Android Multithreading in a UI environment Really simple and useful explanation about threading.i was searching like this.thanks
Posted Mar 30, 2012

yan on Memory Game Android Application hello sir. sorry to interrupt you. can you make some explanation from the source code and the flowchart for this...
Posted Mar 21, 2012

Sujay on Memory Game Android Application I have downloaded the source code .Its nice game.You have given a spinner that shows a dropdown and on selecting...
Posted Mar 19, 2012

2012 Everyday Developer

Admired Theme

converted by Web2PDFConvert.com

You might also like