Android 线程 实例介绍

openkk 12年前

import android.app.Activity;  import android.os.Bundle;  import android.os.Handler;  import android.os.Message;  import android.view.View;  import android.widget.Button;  import android.widget.TextView;    public class EX3Activity extends Activity {   public static final int UPDATE_DATA = 0;   public static final int UPDATE_COMPLETED = 1;   TextView mTextView;   Button mButton;     Handler mHandler = new Handler() {    public void handleMessage(Message msg) {     switch (msg.what) {     case UPDATE_DATA:      mTextView.setText("正在更新来自线程的数据:" + msg.arg1 + "%......");        break;       case UPDATE_COMPLETED:      mTextView.setText("已完成来自线程的数据");      break;     }      }   };     /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);      setContentView(R.layout.main);    mTextView = (TextView) findViewById(R.id.textView1);    mButton = (Button) findViewById(R.id.button1);    mButton.setOnClickListener(new View.OnClickListener() {       @Override     public void onClick(View v) {  //     TODO Auto-generated method stub       new Thread() {       @Override       public void run() {       // TODO Auto-generated method stub             for (int i = 0; i < 100; i++) {       try {       Thread.sleep(30);       } catch (Exception e) {       // TODO: handle exception       e.printStackTrace();       }       Message m = mHandler.obtainMessage();       m.what = UPDATE_DATA;       m.arg1 = i + 1;       mHandler.sendMessage(m);       }       mHandler.sendEmptyMessage(UPDATE_COMPLETED);       }       }.start();           }    });     }    }