学习心得
- post*方法中的Runnable参数中的run代码会在主线程中执行
- 总结非主线程更新UI的4非方法:Handler传递Message消息、调用Activity的runOnUIThread方法、通过handler.post*方法、AsynTask方法
代码样例
/**
* Created by Rambo
*/
public class MyActivity extends MainActivity {
private EditText myEditText = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myEditText = (EditText) findViewById(R.id.myEditText);
final Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
new Thread(new Runnable() {
@Override
public void run() {
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
for (int i=0; i<5; i++){
try {
Log.v(TAG, "main Thread:" + Thread.currentThread().getName());
Thread.sleep(500);
myEditText.setText(Thread.currentThread().getName() + ":" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, 1000);
for (int j=0; j<5; j++){
try {
Thread.sleep(500);
Log.v(TAG, "New Thread:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
网友评论