线程是处理异步任务最常用的方法,下面演示使用线程去更新UI线程的方法使用。
示例:
public class TestThreadActivity extends Activity{
private TextView t1;
private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.textView1);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
test1(); //演示1,主要使用了UI线程的runOnUiThread方法
break;
case R.id.button2:
test2(); //演示2,主要使用操作对象的postDelayed(Runnable, long)方法
break;
default:
break;
}
}
//处理线程问题的方法,可以runnable对象"看成是"子线程运行的代码
private void test1() {
new Thread(new Runnable() {
@Override
public void run() {//子线程运行代码的入口
try {
Thread.sleep(5000); //为了方便观察,休眠5s
} catch (InterruptedException e) {
e.printStackTrace();
}
TestThreadActivity.this.runOnUiThread(new Runnable() { //runnable对象
//把发送到事件队列
@Override
public void run() {
// 这里可执行UI更新
t1.setText("boom,boom,boom......../.");
}
});
}
}).start();
}
private void test2() {
t1.postDelayed(new Runnable() {
@Override
public void run() {
Log.e("ql debug", ">>>>"+Thread.currentThread());
t1.setText("boom,boom,boom......../.");
}
}, 5000);
}
}