This can be simply performed by the use of the AsyncTask class. However, AsyncTask has proven to be a slower approach than a combination of the Thread and Handler classes.
In this post, I shall demonstrate a simple use of these classes, in order to provide a quick interaction between a background thread and the main (UI) thread.
First, let's create a simple Activity and a Thread to perform a simple task.
public class MainActivity extends Activity {
private Handler mHandler;
private BackgroundThread mBackgroundThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
This class contains a Handler and a BackgroundThread class, which is a class we can create, inheriting from Thread, and where we will run our background work. It looks like this:
class BackgroundThread extends Thread implements Runnable {
private Handler handler;
private Message message;
BackgroundThread (Handler h){
handler = h;
}
// Runs on a background thread
@Override
public void run() {
int result = doStuffInBackground();
message = handler.obtainMessage();
message.arg1 = result;
handler.sendMessage(message);
}
int doStuffInBackground(){
//Do your background processing here...
return 0;
}
}
The Handler class, which is passed as an argument to the BackgroundThread constructor looks something like this:
mHandler = new Handler(){
// Runs on the UI thread
public void handleMessage(Message msg) {
int result = msg.arg1;
// Here you can update your UI, safely
}
};
So, as you can see, we can run some code in the run() method in the BackgroundThread class. When it is finished we can call handler.sendMessage(message); and the method handleMessage(Message msg) in the Handler class will be invoked. In this method, you can make whatever changes you want to make in the UI. To pass stuff between the BackgroundThread and the Handler class, you use the Message class. With Message you can even send Objects to the Handler, quickly and safely.In the end, it will look like this:
public class MainActivity extends Activity {
private Handler mHandler;
private BackgroundThread mBackgroundThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler(){
// Runs on the UI thread
public void handleMessage(Message msg) {
int result = msg.arg1;
// Here you can update your UI, safely
}
};
mBackgroundThread = new BackgroundThread(mHandler);
mBackgroundThread.start();
}
class BackgroundThread extends Thread implements Runnable {
private Handler handler;
private Message message;
BackgroundThread (Handler h){
handler = h;
}
// Runs on a background thread
@Override
public void run() {
int result = doStuffInBackground();
message = handler.obtainMessage();
message.arg1 = result;
handler.sendMessage(message);
}
int doStuffInBackground(){
//Do your background processing here...
return 0;
}
}
}
Just don't forget to create the BackgroundThread and invoke the run() method by calling backgroundThread.start()