android - Android上下文线程检查

标签 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");
}

最佳答案

我不明白您的问题,但我想我的回答很明确:
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/

相关文章:

c# - 互锁 Monitor.Enter 和 Monitor.Exit block

c - 锁定 api 的正确约定是什么?

c++ - 原始类型上的多线程和 operator++

java - 为什么我的程序不等待线程中的动画?

android - 有没有办法使用 Android 的 LifecycleObserver 来通知 onActivityResult?

android - 与当前 View 相关的问题

android - 在哪里可以找到 Google Consent SDK 的 consentform.html?

android - Android 中的打印 API

android - *被动*收听 gps 位置更新

java - 增加踏板数量会导致循环持续时间更长