*Activity.runOnUIThread(Runnable)
*View.post(Runnable),View.postDelay(Runnable,long)
*View.post(Runnable),View.postDelay(Runnable,long)
*Handler
*AsyncTask
下面用一个工程实现了上面四种交互方法
public class MainActivity extends Activity {
private TextView txView;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i("RootyInfo", "oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txView=(TextView)findViewById(R.id.textView1);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//创建一个用于展示前三种后台线程和UI线程交互的线程
new TestThread(MainActivity.this).start();
//创建一个用于展示AsyncTask实现交互的TestAsyncTask
new TestAsyncTask().execute("Test"," AsyncTask");
}
});
}
class TestAsyncTask extends AsyncTask<String, Integer, String>
{
//TestAsyncTask被后台线程执行后,被UI线程被调用,一般用于初始化界面控件,如进度条
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
//doInBackground执行完后由UI线程调用,用于更新界面操作
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
txView.setText(result);
super.onPostExecute(result);
}
//在PreExcute执行后被启动AysncTask的后台线程调用,将结果返回给UI线程
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuffer sb=new StringBuffer();
for (String string : params) {
sb.append(string);
}
return sb.toString();
}
}
//用于线程间通信的Handler
class TestHandler extends Handler
{
public TestHandler(Looper looper) {
super(looper);
// TODO Auto-generated constructor stub
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
System.out.println("123");
txView.setText((String)msg.getData().get("tag"));
super.handleMessage(msg);
}
}
//后台线程类
class TestThread extends Thread
{
Activity activity;
public TestThread(Activity activity) {
this.activity = activity;
}
@Override
public void run() {
//下面代码用来演示Activity.runOnUIThread(Runnable)方法的实现
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
txView.setText("Test runOnUIThread");
}
});
//下面代码用来演示Activity.runOnUIThread(Runnable)方法的实现
txView.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
txView.setText("Test View.post(Runnable)");
}
});
//下面代码用来演示Activity.runOnUIThread(Runnable)方法的实现
txView.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
txView.setText("Test View.postDelay(Runnable,long)");
}
}, 1000);
//下面代码用来演示Handler方法的实现
Message msg=new Message();
Bundle bundle=new Bundle();
bundle.putString("tag", "Test Handler");
msg.setData(bundle);
new TestHandler(Looper.getMainLooper()).sendMessage(msg);
super.run();
}
}
}