Sponser

create your own banner at mybannermaker.com!

Monday, March 7, 2011

How to run a Runnable thread or UI thread in Android?

On the launching time of the application itselef the system creates a thread called "main" in the application. This main thread is also called as UI thread, it will only interact with the components of Android UI toolkit.

Here is an example for using the runnable thread in a click event, while clicking the image will be loaded, as it will take time to load the image, we can use the thread as shown below :

Java

public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bm = loadImage();
mImage.post(new Runnable() {
public void run() {
mImage.setImageBitmap(bm);
}
});
}
}).start();
}



Using Handler in Runnable thread


Here we are using the runnable thread using the handler. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.



Java

public class ProgressThread extends Activity implements Runnable {
private String result;
private TextView showResult;
private ProgressDialog progress;
@Override
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
setContentView(R.layout.main);
showResult = (TextView) this.findViewById(R.id.main);
showResult.setText("Press any key to start calculation");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
progress = ProgressDialog.show(this, "Working..", "Calculation is going on...", true,
false);
Thread thread = new Thread(this);
thread.start();
return super.onKeyDown(keyCode, keyEvent);
}
public void run() {
result = MyClass.calculate(800).toString();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
showResult.setText(result);
}
};
}


The runnable thread can be called like this way too


Java

final Runnable runner = new Runnable()
{
public void run()
{
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};

handler.postDelayed(runner, 1000);


Otherwise we can use the original runnable thread that we are using in the java


Java

Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(runner);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

thread.start();


Have a good day.

4 comments:

  1. Nice Thread Tutorial, i am new in android , its help me a lot ...

    I have got some good links

    here
    at androidexample.com
    Thread_With_Handlers

    ReplyDelete
  2. why you are using post in first example
    mImage.("post")(new Runnable() {
    public void run() {
    mImage.setImageBitmap(bm);
    }

    ReplyDelete

Sponser