Like many other native applications, Android applications are also single threaded. There is only one thread ie., the UI thread in the application. So for performing a continuous activity, you need to create a separate worker thread and run it. But you cannot update the UI components from that worker thread you have created. UI components have to be played upon only from the UI thread, failing to do so will lead to unpleasant user experience.
Android provides a number of ways to update UI components from a different worker thread. One of them is using the runOnUiThread method on Activity class, which accepts the Runnable object.
Say you want to display the current date and time in a TextView object from a separate thread. This is how you can do it.
final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
this.runOnUiThread(new Runnable(){
public void run(){
dateTxt.setText(new Date().toString());
}
});
dateTxtView is a TextView component. This code starts a separate thread but accesses the dateTxt component from the UI thread only.
What if you want to update the time every one second, let’s use a java.util.Timer class for this purpose. The Timer will run for 1000 milliseconds. The code is shown below.
final TextView dateTxt = (TextView)findViewById(R.id.dateTxtView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable(){
public void run() {
dateTxt.setText(new Date().toString());
}
});
}
}, 0, 1000);
The Timer class’ schedule method accepts a TimerTask instance that starts a thread, after a delay of 0 seconds, and runs every 1000 milliseconds . This thread encapsulates another worker thread that updates the dateTxt with the latest time.