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.