【问题标题】:ThreadException - Event most of the time occurs on UI Thread but sometimes on another ThreadThreadException - 事件大部分时间发生在 UI 线程上,但有时发生在另一个线程上
【发布时间】:2015-02-27 13:29:15
【问题描述】:

我有一个方法可以从网络获取Object,然后用这些数据更新UI

我使用第三方 API 来获取数据并接收数据。 下载过程在新的Thread 中完成,并在UI Thread 中完成数据的获取和更新。

在我的主线程中:

public void getNetRequest (DownloaderRequest netRequest) {
        carImage.setBackgroundResource(netRequest.imageResource);
    }

在 85% 的情况下,这段代码在 UI 线程上运行,但有时在 15% 的时间内我会遇到异常:

    [DownloaderForRequests]android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)

.
.
.
at java.lang.Thread.run(Thread.java:841)

当我调试它时,我看到 getNetRequestMain Thread 中调用,但异常说它是在 DownloaderForRequests Thread 上调用的。 我添加了一个日志用于检查当前线程,它表明发生此异常时它确实不是主线程。

为什么它很少发生,我如何测试它并 100% 修复它? 我不想使用runOnUiThread,因为它不会解决问题我想检测它并理解问题,而不是无缘无故地添加更多代码。

【问题讨论】:

  • 我们需要更多代码来帮助您。
  • 好像可以使用AsyncTask
  • 请提供(至少与线程相关的)DownloaderRequest 代码。

标签: java android multithreading thread-safety


【解决方案1】:

您可以检查哪个线程,例如

if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    method();
                }
            });
        }else{
            method();
        }

【讨论】:

  • 谢谢你的回答,但我想了解为什么它会在 15% 的时间内发生,所以我也可以在其他地方修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2015-04-24
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
相关资源
最近更新 更多