Wednesday, April 15, 2015

Performing UI Related task from Worker Thread using Handler

This Example shows How to do UI related task from Worker Thread using Handler. Main Thread contains Handler object. Which ever thread creates Handler object receives message from other thread (Handler Handles the Message).


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

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);

// UI thread creates object of Handler.  
mHandler = new Handler();

new Thread(new Runnable() { // Worker Thread
// Sending Runnable to Handler MessageQueue which will handled in UI Thread
@Override
public void run() {
mHandler.post(new Runnable() { 
@Override
public void run() {
// Showing Toast Message
Toast.makeText(getApplicationContext(), "I am from Worker Thread", Toast.LENGTH_LONG).show();
}
});
}
}).start();  // Starting Thread
}
}
 

No comments:

Post a Comment