WEB开发网
开发学院手机开发Android 开发 Android 线程 实例介绍 阅读

Android 线程 实例介绍

 2012-06-09 13:34:02 来源:WEB开发网   
核心提示: package gongzibai.co.cc;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;impor

 package gongzibai.co.cc;

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();

}
});

}

}

Tags:Android 线程 实例

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接