在android开发过程中,我们经常有通过子线程来更新界面UI的需求,而android是不允许子线程更新界面的,只能通过主线程来更新界面UI,而且,android开发中,由于要保证主线程的通畅,一般主线程只负责处理界面更新,事件处理,窗体显示的回调等重要且不耗时的操作,而像连接网络,io操作等,一般让子进程负责。
所以,android提供了一种消息机制来实现子线程更新UI的需求,android提供Handler类,用于子线程和主进程交互。在主进程中,声明实例化一个Handler,并重写它的handleMessage方法。
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
int i = (Integer) msg.obj;
tView.setText("hello world "+i);
super.handleMessage(msg);
}
};
在子线程中,调用的Handler的sendMessage方法,android主线程就会调用HandleMessage方法来处理。
Thread thread = new Thread(){
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
try {
sleep(500);
} catch (Exception e) {
// TODO: handle exception
}
Message msg = new Message();
msg.obj = i;
handler.sendMessage(msg);
}
super.run();
}
Handler
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。