我目前正在开发的一个应用程序正在与服务器通信,通信过程在其自己的线程中运行。有异步调用 - 例如login()和onLoginResponse()。
login()在主活动中被调用,并且响应也在主活动中处理(onLoginResponse())。在onLoginResponse()方法中,有一个updateGUIState()方法,它修改布局元素:
private void updateGUIState() {
Log.i(TAG, "executing updateGUIState");
arrangeLayoutElements();
txtTime.setText(mStrRecordingTime);
if (settings.isRecording()) {
//btnAction.setText("Stop");
btnAction.setImageResource(R.drawable.button_stop);
} else {
//btnAction.setText("Capture");
btnAction.setImageResource(R.drawable.button_record);
}
//set privacy level text
if (settings.getPrivacyLevel() == 0) {
txtPrivacyLevel.setText("Private");
} else if (settings.getPrivacyLevel() == 1) {
txtPrivacyLevel.setText("Public");
}
if (settings.isMute()) {
muteIcon.setIconImage(R.drawable.ic_volume_off_small);
} else {
muteIcon.setIconImage(R.drawable.ic_volume_small);
}
if (mIsUploading) {
txtUploadingText.setVisibility(View.VISIBLE);
uploadingProgressBar.setVisibility(View.VISIBLE);
} else {
txtUploadingText.setVisibility(View.INVISIBLE);
uploadingProgressBar.setVisibility(View.INVISIBLE);
}
if (mEncoderConnection != null) {
txtConnectionStatus.setText("Connected");
} else {
txtConnectionStatus.setText("Disconnected");
}
}
当执行到这个方法时(从onLoginResponse()调用),应用程序会崩溃,并且日志显示以下消息:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
有没有人知道如何修改逻辑,以便在修改布局之前切换到适当的线程并解决问题?
谢谢!