要开辟一个新的线程,主要用到两个类,一个是Thread,一个是Handler,Thread是用来开启线程,并传递Message信息给Handler,然后Handler根据接收到的Message来决定要执行什么样的操作。下面是一个简单的小例子,进行辅助说明。
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" />
<Button android:id="@+id/my_button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="test" />
<TextView android:id="@+id/my_TextView" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="hello" />
</LinearLayout>
比较简单,就是定义了三个组件,两个TextView,一个Button。
package com.test.androidtest;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class AndroidTestActivity extends Activity {
private Button myButton;
private TextView myTextView;
private Handler myHandler;
/** Called when the activity is first created. */
@Override
//整个onCreate函数里面就是我们的UI主线程
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化组件
myButton = (Button)findViewById(R.id.my_button);
myTextView = (TextView)findViewById(R.id.my_TextView);
//给按钮设置监听器
myButton.setOnClickListener(new myButtonListener());
//定义新的Handler,根据传递过来的message信息确定执行什么操作
//主线程中的Handler会一直处于等待状态,直到新线程有message传递过来
myHandler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case 1:
myTextView.setText("the new thread!");
myTextView.setBackgroundColor(Color.BLUE);
break;
default:
break;
}
}
};
}
class myButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//开辟一个新的线程
new Thread(){
public void run(){
//下面三句话是定义个新的Message,并传递一个值给主线程中的Hander
Message msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
}
}.start();
}
}
}
结果如下:
点按钮后: