How to update UI from a different thread
Google has set it’s tone on some tough guidelines for developing android apps, basically there aren’t any strict rules but one very easy to misunderstand.
there is a single Thread which is called the “main” thread, or “UI thread” on some places. this is the thread which is in charge on the views and interaction with the users gestures.
based on the guidelines of any mobile platform at the moment, all the work that shouldn’t be done on the main thread should be done on background thread. this can be achieved in many ways, you can use AsyncTask, Or A Handler, Or a simple thread with an implementation of the run() method within the declaration of the runnable.
ok, so if I’m pulling some server data, or performing long calculations, pulling stuff from or to the Sqlite database I’ll probably use an AsyncTask.
but let’s say for instance that I want to simply update the UI once every couple of seconds (update a TextView or an ImageView’s content etc..), here’s a simple example of implementing this by a Handler :
package com.example.androidthreadspractice;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
int num1=0,num2=0;
Handler mHandler = new Handler();
TextView tv1,tv2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
tv2=(TextView)findViewById(R.id.tv2);
Runnable runnable = new Runnable() {
@Override
public void run() {
{
tv1.setText(String.valueOf(num1)+" ");
tv2.setText(String.valueOf(num2)+" ");
num1++;
num2+=10;
if (num1<10)
{
mHandler.postDelayed(this, 1000);
}
}
}
};
mHandler.post(runnable);
}
}
let’s see what we’ve got:
- 2 TextViews, 2 integers which will change their value.
- we define a Handler.
- we define a Runnable object with the run() method which will change the values of num1,num2 and update the TextViews accordingly with the new values, until num1<20 (we do mHandler.postDelayed() for “sleeping” 1 second.
- after defining the Runnable we simple do mHandler.post(runnable) which Causes the Runnable to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
this task could be easily implemented with CountDownTimer class but I chose to demonstrate it using a Handler and a Runnable.
Comments