代码之家  ›  专栏  ›  技术社区  ›  Michel

无法用处理程序解析CalledFromWronThreadException

  •  2
  • Michel  · 技术社区  · 14 年前

    我会尽量保持简单:

    在我的主要活动中,我做了一个处理程序:

    public class ARViewer extends ARDisplayActivity {
    
        public final MHandler mHandler = new MHandler(this);
    
     public void onCreate(Bundle savedInstanceState) {
    ...
    

    mhandler类:

    public final class MHandler extends Handler{
    
            //main activity
     private ARViewer arnv;
    
            public MHandler(ARViewer arnv){
      this.arnv = arnv;
     }
    
            @Override
     public void handleMessage(Message msg) {
                ...
                case H_RR :
                      arnv.setContentView(R.layout.routeplanner);    
                      break;
                ...
      super.handleMessage(msg);
     }
    }
    

    但是,如果我从另一个类中的回调函数调用handleMessage方法,当然是从另一个线程调用,我仍然会收到异常消息: CalledFromWrongThreadException (Only the original thread that created a view hierarchy can touch its views) :

    public void rFound(Route route) {
               Message msg = new Message();
               msg.what = MHandler.H_RR;
               ARViewer.arnv.mHandler.handleMessage(msg);
    }
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   Alex Volovoy    14 年前

    你不需要参考那里的活动。 在做用户界面的地方创建新的runnable。做mhandler.post(myuirunnable); 示例如下: http://developer.android.com/guide/appendix/faq/commontasks.html#threading

        2
  •  0
  •   Karan    14 年前

    您应该为处理程序调用sendmessage(),消息ID为h_rr。这将自动调用主线程中的handleMessage()。