Multithreading in A UI Environment
Multithreading in A UI Environment
http://www.aviyehuda.com
Previous
Next
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(); }
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
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
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:
Share
Share
Like
This entry was posted in Android and tagged Android, multithreading by Avi. Bookmark the permalink.
Very neatly written and explained. But only gripe is, code could have used better formatting / syntax highlighting JS. Even otherwise, an excellent article.
Reply
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
converted by Web2PDFConvert.com
Reply
gooodddddddd
Reply
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
Its really a great tutorial on Complete thread handling in android .. Thank you so much for publishing so nice tutorial.
Reply
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
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
The Best!
Reply
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
Really simple and useful explanation about threading.i was searching like this.thanks
Reply
> Notice that AsyncTask has 4 operations, which are executed by order. Shouldnt that order be 1,3,2 ????
Reply
converted by Web2PDFConvert.com
> 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
Leave a Reply
Your email address will not be published. Name
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
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
Admired Theme
converted by Web2PDFConvert.com