main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="200dp" android:layout_height="wrap_content" android:visibility="gone" /> <Button android:id="@+id/startButton" android:layout_width="65dp" android:layout_height="36dp" android:text="start" /> </LinearLayout> BarHandlerActivity.java package archie.android.handler; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class BarHandlerActivity extends Activity { private Button startButton; private ProgressBar progressBar; private static final String TAG="tag"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startButton=(Button) findViewById(R.id.startButton); progressBar=(ProgressBar) findViewById(R.id.progressBar); startButton.setOnClickListener(new ButtonListener()); } class ButtonListener implements OnClickListener{ @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE); updateBarHandler.post(updateThread); } } //使用匿名内部类来复写Handler当中的HandleMessage方法 Handler updateBarHandler=new Handler(){ @Override public void handleMessage(Message msg) { //从消息队列中得msg的一个成员 progressBar.setProgress(msg.arg1); updateBarHandler.post(updateThread); super.handleMessage(msg); } }; //线程类,该类使用匿名内部类的方式进行声明 Runnable updateThread=new Runnable() { int i=0; @Override public void run() { Log.v(TAG, "Begin Thread"); i=i+10; //得到一个消息对象,Message类是由Android操作系统提供 Message msg=updateBarHandler.obtainMessage(); //将msg对象的arg1参数的值设置为i //用arg1和arg2两个成员变量传递消息,系统性能消耗少 msg.arg1=i; try{ Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); } //将msg对象加入到消息队列中 updateBarHandler.sendMessage(msg); if(i==100){ //如果当i的值为100时,将线程对象从handler中移除 updateBarHandler.removeCallbacks(updateThread); } } }; }