final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_OK:
rl_loading.setVisibility(View.GONE);
break;
}
super.handleMessage(msg);
}
}; new Thread(new Runnable() { @Override
public void run() {
try {
Message message = new Message();
message.what = MSG_OK;
handler.sendMessage(message);
} catch (Exception e) {
}
}
}).start();
如上:在新线程的run中完成耗时操作,完成后用消息的方式通知主线程。
另外,Android中的Timer也是用类似的的方式实现的,Timer负责定时发送消息,主线程中完成操作:
TimerTask task = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
Timer timer = new Timer(true);
timer.schedule(task, 1000, 10000); // 延时1s后执行,10s执行一次