Android的CalledFromWrongThreadException [英] Android CalledFromWrongThreadException

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

问题描述

我已经看到了很多关于这个主题的问题,但我真的不是高兴与任何答案。

我想什么它有一个类ConnectionController实现Runnable 是负责打开连接如服务器,读取和写入消息,并有自被实例化开始通过端的应用程序。

我有一个类MainActivity从活动来延长是的onCreate它将实例化一个ConnectionController对象。

这connectionController有更改MainActivity一些字段(并最终在另一个活动),如状态conections ImageView的,例如,或者甚至接收到的消息的TextView

由于connectionController是主题我无法访问元素(CalledFromWrongThreadException(只有创建视图层次可以触摸其观点原来的线程)。

你有什么推荐使用?我看到了异步任务,处理程序解决方案,myUIRunnable但我不明白什么是这种情况的最佳解决方案。

先谢谢了。


解决方案

  

这connectionController有更改MainActivity一些字段(并最终在另一个活动),如状态conections ImageView的,例如,或者甚至接收到的消息的TextView


没有,没有。它需要的安排的那些东西被改变。既然你选择作出控制是出于某种原因一个线程,该控制器不能改变这些UI元素本身。


  

你有什么推荐使用?


使用后()查看。或者,使用 runOnUiThread()上的活动。或者,使用处理程序

I've seen a lot of questions about this subject but i'm really not happy with any answer.

What i want its to have a class ConnectionController implements Runnable that is responsible for opening the conection to server, read and write messages to it and have to be instantiated since the beginning of the application through the end.

I have a class MainActivity extends from Activity that onCreate it will instantiate a ConnectionController object.

That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

Because connectionController is a Thread i cannot access to elements (CalledFromWrongThreadException (Only the original thread that created a view hierarchy can touch its views).

What do you recommend to use? I saw solution with async tasks, handlers, myUIRunnable but i didn't understand what is the best solution for this situation.

Thanks in advance.

解决方案

That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

No, it does not. It needs to arrange for those things to be changed. Since you elected to make a "controller" be a thread for some reason, the controller cannot change those UI elements itself.

What do you recommend to use?

Use post() on a View. Or, use runOnUiThread() on an Activity. Or, use a Handler.

这篇关于Android的CalledFromWrongThreadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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