Android Pro - Blogspot.com 2011 05 Threading in Android Part1
Android Pro - Blogspot.com 2011 05 Threading in Android Part1
Page 1 of 6
Multi-Threading concept is essential in most platforms. it provides maximum utilization of the processor. threadingis used when the program executes time consuming processes (such as calling a web service)and to givea good user experience by unblocking the UI. Android provides threading techniques to perform time consuming tasks in a background thread with coordination with the UI thread to update the UI. Android provides the followingmethods of threading: 1. Handlers. 2. Async. Tasks.
Handlers:
When you create an object from the Handler class, it processes Messages and Runnable objects associated with the currentthread MessageQueue. the message queue holds the tasks to be executed in FIFO (First In First Out) mannser.you will need only ine Handler per activity where the background thread will communicate with to update the UI. The Handler is associated with the thread from which it's been created We can communicate with the Handler by two methods: 1. Messages. 2. Runnable objects. In this post we will demonstrate how to use both using a simple example which is updating the text of a TextView using multiple threads.
Using Messages:
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011
Page 2 of 6
the steps of using a Handler are as follows: 1. You create a Handler object with an asscociated callback method to handle the received messages (it is the method where the UI update will be done). 2. From the background thread you will need to send messages to the handler. Here's the code of our activity:
public class MainActivity extends Activity { TextView txt; // our handler Handler handler = new Handler() { @Override public void handleMessage(Message msg) {
//display each item in a single line txt.setText(txt.getText()+"Item "+System.getProperty("line.separator")); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txt=(TextView)findViewById(R.id.txt); } @Override protected void onStart() { super.onStart(); // create a new thread Thread background=new Thread(new Runnable() { @Override public void run() { for(int i=0;i<10;i++) { try { Thread.sleep(1000); Key", "My Value:
b.putString("My
"+String.valueOf(i)); // send message to the handler with the current message handler handler.sendMessage(handler.obtainMessage()); } catch (Exception e) { Log.v("Error", e.toString()); } } }
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011
Page 3 of 6
}); background.start(); } }
after running the following code theTextView will display the following, each second a new line is written:
This example is pretty basic, it just sends the same message for a number of times. what if we want the message sent to hold data that's changed each time the message is sent, the answer is to use Message.setData(Bundle bundle) method by creating a Bundle object and adding the data to it like this:
public class MainActivity extends Activity { TextView txt; // our handler Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // get the bundle and extract data by key Bundle b = msg.getData(); String key = b.getString("My Key"); txt.setText(txt.getText() + "Item " + key +System.getProperty("line.separator")); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011
Page 4 of 6
txt = (TextView) findViewById(R.id.txt); } @Override protected void onStart() { super.onStart(); // create a new thread Thread background = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); Message msg = new Message(); Bundle b = new Bundle(); b.putString("My Key", "My Value: " + String.valueOf(i)); msg.setData(b); // send message to the handler with the current message handler handler.sendMessage(msg); } catch (Exception e) { Log.v("Error", e.toString()); } } } }); background.start(); } }
we put a string to the bundle and send a message with that bundle. in the handler method we receive the bundle and get the value with the predefined key. after executing that code the text view would look like this:
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011
Page 5 of 6
Using Runnables:
another way to use Handlers is to pass them a Runnable by using the Handler.post() method like this:
Runnable r=new Runnable() { @Override public void run() { txt.setText("Runnable"); } }; handler.post(r);
this will add the Runanble object to the message queue to be executed by the handler.
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011
Page 6 of 6
All the above messages return a boolean indicating whether the message or the runnable has been placed successfully in the message queue.
http://android-pro.blogspot.com/2011/05/threading-in-android-part-1-handlers.html
9/20/2011