在 Android 中,视图组件并不是线程安全的。出于线程保护,Android 会拒绝子线程对主线程 UI 的更新,并抛出如下异常:
Only the original thread that created a view hierarchy can touch its views.
所以,要跨线程更新 UI,需要使用 Handler 技术。
具体代码
private static final int PUSH_RECEIVED = 0;
private static final int GET_BASIC_INFO = 1;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
if(message.what == PUSH_RECEIVED) {
statusTextView.setText("异常");
}
if(message.what == GET_BASIC_INFO) {
nameTextView.setText(nameText);
statusTextView.setText(statusText);
rateTextView.setText(rateText);
recordTextView.setText(recordText);
}
}
};
Message message = new Message();
message.what = PUSH_RECEIVED;
handler.sendMessage(message);
子线程通过 Handler 通知主线程更新 UI,主线程收到消息后,在线程中对 UI 进行更新。