Wednesday, April 15, 2015

Sending message from one worker thread to other worker thread using Handler and Looper (Android)

Below code snippet explains how to send message from one worker thread to another worker thread using Handler, Looper and Message. First worker thread receive message from second thread.



import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class Testing extends Activity {

//Handler Basically does Two task 1) Handle Message in current thread 2) Send to other Thread for proccessing
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new Thread(new Runnable() {   // First worker Thread
@Override
public void run() {
                                // Prepare a Massage Queue for Handler so one by one can be processed
Looper.prepare(); 
mHandler = new Handler() { // Handler is associated with current thread
 // Handling Received Messages
                                       @Override
public void handleMessage(Message msg) {  
super.handleMessage(msg);
System.out.println("Recived By " + Thread.currentThread().getName() + " And Msg is: " + msg.arg1);

}
};
Looper.loop();

}
}).start();

new Thread(new Runnable() {   // Second  Worker Thread
@Override
public void run() {
int i = 0;
while (i < 100) {
/*Obtain a Message from Message Pool. It's good practice not to create Message Object but get from System itself. Saves memory.*/
Message msg = Message.obtain();
System.out.println("Sending MSg via: " + Thread.currentThread().getName() + "Data: " + i);
msg.arg1 += i;
mHandler.sendMessage(msg); // Sending Message to 1st worker thread
i++;
}
}
}).start();
}
}

No comments:

Post a Comment