貌似这个看起来比较合理:
package com.example;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Looper_8 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;
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.setBackgroundResource(R.drawable.icon);
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.setBackgroundResource(R.drawable.icon);
btn2.setText("exit");
btn2.setOnClickListener(this);
layout.addView(btn2, param);
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:
progressDialog = ProgressDialog.show(this, "please wait…",
"Loading", true);
//生成主线程的handle
h = new EventHandler(Looper.myLooper());
th1 = new myThread();
th1.start();
break;
case 102:
finish();
break;
}
}
// ------------------------------------------------
public class EventHandler extends Handler {
public EventHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
setTitle((String) msg.obj);
}
}
// ---------------------------------------
class myThread extends Thread {
@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);
}
}
}