2010年1月31日 星期日

Thread& Handler

Activity:

public class ThreadAndHandler extends Activity implements OnClickListener {
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
private ProgressDialog progressDialog = null;
private myThread th1;
public TextView tv;
private Button btn, btn2, btn3;
private EventHandler h;

public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

btn = new Button(this);
btn.setId(101);
btn.setText("test looper");
btn.setOnClickListener(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(100, 50);
param.topMargin = 10;
layout.addView(btn, param);

btn2 = new Button(this);
btn2.setId(102);
btn2.setText("exit");
btn2.setOnClickListener(this);
layout.addView(btn2, param);

btn3 = new Button(this);
btn3.setId(103);
btn3.setText("send message");
btn3.setOnClickListener(this);

tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setText("");
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(FP, WC);
param2.topMargin = 10;
layout.addView(tv, param2);
setContentView(layout);
// ------------------------
}

public void onClick(View v) {
switch (v.getId()) {
case 101:
String dialogTitle = "please wait…";
progressDialog = ProgressDialog.show(this, dialogTitle,
"Loading", true);
h = new EventHandler(Looper.myLooper());
//h = new EventHandler();
th1 = new myThread();
th1.start();
break;
case 102:
finish();
break;
}
}

// ------------------------------------------------
public class EventHandler extends Handler {
public EventHandler(){
super();
}
public EventHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
tv.setText(msg.toString());
//Toast.makeText(ThreadAndHandler.this, msg.toString(), Toast.LENGTH_LONG).show();
setTitle((String) msg.obj);
}
}

// ---------------------------------------
class myThread extends Thread implements Runnable{
@Override
public void run() {
try {
sleep(6000);
} catch (Exception e) {
e.printStackTrace();
}
String obj = "mainThread....";
Message m = h.obtainMessage(1, 1, 1, obj);
h.sendMessage(m);
}
}
}



Reference:
http://www.android1.net/Topic.aspx?BoardID=11&TopicID=701
http://www.android1.net/Topic.aspx?BoardID=11&TopicID=625