Android CalledFromWrongThreadException

标签 android multithreading exception status

我已经看到很多关于这个主题的问题,但我对任何答案都不满意。

我希望它有一个 class ConnectionController implements Runnable 负责打开到服务器的连接,读取和写入消息,并且必须从应用程序开始时通过结束。

我有一个类 MainActivity extends from Activity,onCreate 它将实例化一个 ConnectionController 对象。

connectionController 必须更改 MainActivity 上的某些字段(并最终在其他 Activity 中)​​,例如状态连接 ImageView,甚至接收消息 TextView。

因为 connectionController 是一个线程,我无法访问元素(CalledFromWrongThreadException(只有创建 View 层次结构的原始线程才能触及它的 View )。

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

提前致谢。

最佳答案

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.

不,它没有。它需要安排更改这些内容。由于您出于某种原因选择将“ Controller ”设为线程,因此 Controller 无法自行更改这些 UI 元素。

What do you recommend to use?

View 上使用 post()。或者,在 Activity 上使用 runOnUiThread()。或者,使用 Handler

关于Android CalledFromWrongThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9554928/

相关文章:

android - Actionbar Logo 在展开的 ActionView 上变成应用程序图标

c++ - Boost::thread 中的 join() 究竟是什么? (C++)

android - Lollipop Activity 共享元素过渡与淡入淡出

java - Java 中没有同步的线程安全单例?

c++ - 程序关闭时 notify_all() 崩溃

python - 在一行中捕获多个异常(除了 block )

java - NAO Robotics学生在AMD 64位平台上编译错误: Can't load IA 32-bit . dll

python异常消息捕获

Android-Studio:Gradle 找不到 HoloEverywhere

android - AlertDialog 不在列表中显示分隔符