【问题标题】:Can't resolve CalledFromWrongThreadException with Handler无法使用处理程序解决 CalledFromWrongThreadException
【发布时间】:2011-02-18 14:55:00
【问题描述】:

我会尽量保持简单:

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

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

【问题讨论】:

    标签: android exception multithreading


    【解决方案1】:

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

    【讨论】:

    • 我之前找到了这个解决方案,但无法让它发挥作用。我会再看一遍。谢谢
    • 为什么要在线程中设置 setContentView(R.layout.routeplanner) ?将其设置在 onCreate 中,然后通过 findViewById(R.id.myview) 更新您的视图/布局并设置正确的内容/值/可见性
    • 视图(组)比“routeplanner”多得多,所以我想要一个处理所有视图的处理程序
    【解决方案2】:

    您应该调用消息 id 为 H_RR 的 Handler 的 sendMessage()。这会在主线程中自动调用handleMessage()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多