I came across this code in a very basic Handler tutorial. The code is working fine but I do not understand why I have to use Handler for progressDialog.dismiss() ??? I removed the Handler part and placed progressDialog.dismiss() in the run() method and it worked fine. So why used Handler???
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HandlerThread extends Activity{
private Button start;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
fetchData();
}
});
}
protected void fetchData() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(this, "", "Doing...");
new Thread() {
public void run() {
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
}
messageHandler.sendEmptyMessage(0);
}
}.start();
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
}
};
}
From the documentation of
View:In your example, when you’ve to call the
dismiss()method on theProgressDialog, as per the above documentation, you must do so from the UI thread. ThemessageHandleris initialized to an instance of aHandlerwhen theHandlerThreadclass is instantiated (presumably on the UI thread).From the documentation of
Handler:So to communicate with the UI thread from your new thread, just post a message to the
Handlercreated on the UI thread.If you call methods on a
Viewfrom outside the UI thread, it invokes undefined behaviour, which means, it may appear to work fine. But it’s not always guaranteed to work fine.