Android上下文线程检查

时间:2014-09-01 19:48:32

标签: android multithreading

据我所知,UI线程是主线程。 根据文档,getMainLooper是UI线程。

Application上下文线程也不应该是UI线程吗?

此外,Fragment的Looper线程也不应该是UI线程吗?

为什么以下失败(两者)?

if (getActivity().getApplicationContext().getMainLooper().getThread() == Looper.getMainLooper().getThread()) {
    throw new Exception("Context is not the application's thread");
}

//Inside a Fragment
if (new Handler().getLooper().getThread() == Looper.getMainLooper().getThread()) {
    throw new Exception("Handler is not for the main thread");
}

1 个答案:

答案 0 :(得分:0)

我不明白你的问题,但我认为我的回答清楚地说明了:

getActivity().getApplicationContext().getMainLooper().getThread()返回与UI线程或等效主线程关联的线程。

Looper.getMainLooper().getThread()也返回上面的线程。所以它们实际上都是一个对象,因此if条件为真意味着:

“上下文线程 IS 应用程序的线程”

如果您在主线程上,那么new Handler().getLooper().getThread()将返回正好在线程之上。还有Looper.getMainLooper().getThread()因此两个参考实际上指向一个对象,因此条件为真且

处理程序线程 IS 主线程

您可以轻松查看if语句。 : - )

Why the following fails (both)?

不,我认为你对异常意义感到困惑。如果条件为真且条件为真,则抛出异常。这与android异常的含义不同,这是你的自定义,因为条件得到满足,它会正确抛出。