安卓子线程访问UI线程的四种方法

1.第一种

Handler机制:通过Handler+Message实现通信

Message msg = new Message(); msg.what = 0x1234; msg.obj = null; handler2.sendMessage(msg);

2.第二种

Activity.runOnUiThread(runnable);

runOnUiThread(new Runnable() { public void run() { tv.setText("执行完成"); } });

3.第三种

View.post(runnable);

View.post(Runnable)方法。在post(Runnable action)方法里View获得当前线程UI线程Handler然后将action对象postHandler里。在Handler里,它将传递过来的action对象包装成一个MessageMessagecallbackaction),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnablerun方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI

handler.post(new Runnable() { @Override public void run() { tv.setText("执行完成"); } });

4.第四种

View.postDelayed(runnable);

**

handler.postDelayed(new Runnable() { @Override public void run() { tv.setText("执行完成"); } },2000);

*
*

*
*

测试代码

**

package com.study.AndroidPro; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; / * Created by pengwei on 2014/10/10. / public class ThreadTest extends Activity { private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.thread_layout); tv = (TextView) findViewById(R.id.thread_tv); Init(); } private Handler handler2 = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); tv.setText("执行完成"); } }; private Handler handler = new Handler(); public void Init(){ new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //第一种方法 Message msg = new Message(); msg.what = 0x1234; msg.obj = null; handler2.sendMessage(msg); //第二种方法 /runOnUiThread(new Runnable() { public void run() { tv.setText("执行完成"); } });/ //第三种方法 /handler.post(new Runnable() { @Override public void run() { tv.setText("执行完成"); } });/ //第四种方法 /handler.postDelayed(new Runnable() { @Override public void run() { tv.setText("执行完成"); } },2000);/ } }).start(); } }*

*
*