public class MainActivity extends Activity {
private TextView tv;
private Button button;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.buttonId);
tv = (TextView)findViewById(R.id.textViewId);
button.setOnClickListener(new MyButton());
}
class MyButton implements OnClickListener {
@Override
public void onClick(View v) {
Thread t = new MyThread();
t.start();
}
}
class MyThread extends Thread {
@Override
public void run() {
Runnable runnable = new Runnable() {
@Override
public void run() {
//比如这里从网络中获取到了数据吗,在这里直接可以更新主线程中的数据
String currentString = Thread.currentThread().getName();
System.out.println("当前线程的名称为:"+currentString);
tv.setText(currentString);
}
};
handler.post(runnable);
}
}
}
post机制将runnable对象运行在主线程中的