不能与处理程序解决CalledFromWrongThreadException [英] Can't resolve CalledFromWrongThreadException with Handler

查看:127
本文介绍了不能与处理程序解决CalledFromWrongThreadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会尽量保持简单:

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

 公共类ARViewer扩展ARDisplayActivity {    公众最终MHandler mHandler =新MHandler(本); 公共无效的onCreate(捆绑savedInstanceState){
...

类MHandler:

 公共最后一类MHandler扩展了Handler {        //主要活动
 私人ARViewer arnv;        公共MHandler(ARViewer arnv){
  this.arnv = arnv;
 }        @覆盖
 公共无效的handleMessage(消息MSG){
            ...
            案例H_RR:
                  arnv.setContentView(R.layout.routeplanner);
                  打破;
            ...
  super.handleMessage(MSG);
 }
}

但是,如果我把从在其他类的回调函数的handleMessage方法,肯定从其他线程,我仍然得到异常消息: CalledFromWrongThreadException(只有创建一个视图可以分层原来的线程触摸自己的看法)

 公共无效rFound(路由路径){
           消息味精=新的Message();
           msg.what = MHandler.H_RR;
           ARViewer.arnv.mHandler.handleMessage(MSG);
}


解决方案

您不必参考活性那里。
创建新的可运行,你做你的UI的东西。而做mHandler.post(myUIRunnable);
例子如下:
http://developer.android.com/guide/appendix/faq/commontasks html的#线程

I will try to keep it simple:

In my main activity I make a handler:

public class ARViewer extends ARDisplayActivity {

    public final MHandler mHandler = new MHandler(this);

 public void onCreate(Bundle savedInstanceState) {
...

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

But if I call the handleMessage method from a callback function in a other Class, definitely from a other thread, I still get the exception message: 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);
}

解决方案

You don't need reference to activity there. Create new runnable where you doing your UI stuff. And do mHandler.post(myUIRunnable); Example is here: http://developer.android.com/guide/appendix/faq/commontasks.html#threading

这篇关于不能与处理程序解决CalledFromWrongThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆