我当前正在开发的应用程序正在与服务器通信,并且通信过程在其自己的线程中运行。有异步调用-例如login()和onLoginResponse()。

在主要 Activity 中调用login(),并且也在主要 Activity 中处理响应(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()调用时),应用程序崩溃,并且日志显示以下消息:



有谁知道在修改布局和解决问题之前如何修改逻辑以切换到适当的线程?

谢谢!

最佳答案

尝试Handler
onLoginResponse()是回调函数吗?
如果是这样,则可以通过Handler解决该问题。

onLoginResponse()中,

hRefresh.sendEmptyMessage(REFRESH);


    Handler hRefresh = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    switch(msg.what){
         case REFRESH:
                /*Refresh UI*/
                updateGUIState();
                break;
       }
    }
};

关于Android:android.view.ViewRoot $ CalledFromWrongThreadException-如何解决问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1536654/

10-10 20:19