据我所知,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");
}
最佳答案
我不明白您的问题,但我想我的回答很明确:getActivity().getApplicationContext().getMainLooper().getThread()
返回与UI线程或等效的主线程关联的线程。Looper.getMainLooper().getThread()
也返回上述线程。因此它们实际上都是一个对象,因此if条件为true表示:
“上下文线程是应用程序的线程”
如果您在主线程上,则new Handler().getLooper().getThread()
返回恰好在线程之上。以及Looper.getMainLooper().getThread()
,因此这两个引用实际上都指向一个对象,因此条件为true,并且
处理程序线程是主线程
您可以轻松地检查那些if语句。 :-)Why the following fails (both)?
不,我认为您对异常(exception)含义感到困惑。如果条件为真且条件为真,则抛出异常。这与android异常的含义不同,这是您自定义的异常,由于条件满足,它会正确抛出。
关于android - Android上下文线程检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612168/