2010-05-12 86 views
2

解决CalledFromWrongThreadException我会尽量保持简单:无法与处理程序

在我的主要活动我作出处理:

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); 
} 

回答

3

您不需要参考那里的活动。 创建新的可运行的地方,你做你的UI的东西。并做mHandler.post(myUIRunnable); 示例如下: http://developer.android.com/guide/appendix/faq/commontasks.html#threading

+0

我发现此解决方案之前,但无法使其工作。我会再看看它。谢谢 – Michel 2010-05-12 13:15:18

+0

为什么你要在线程中设置setContentView(R.layout.routeplanner)?将它设置在onCreate中,然后通过findViewById(R.id.myview)更新你的视图/布局,并设置正确的内容/值/可见性 – 2010-05-12 13:39:01

+0

还有比'routeplanner'更多的视图(组),所以我想要一个处理程序所有视图 – Michel 2010-05-12 13:45:41

0

您应该为Handler调用sendMessage(),消息标识为H_RR。这将自动调用主线程中的handleMessage()。