2014-09-01 51 views
1

據我所知,UI線程是主線程。 getMainLooper根據文檔是UI線程。Android上下文線程檢查

應用程序上下文線程不應該是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

上下文與Thread無關,默認情況下,任何Android應用程序都有一個主UI線程,並且這是唯一的線程應用程序正在運行 – pskink 2014-09-01 19:53:38

+0

@pskink我同意,但從上下文有可能獲得MainLooper,然後它屬於的線程。此線程不應該與UI線程匹配嗎? – igorjrr 2014-09-01 20:16:59

+0

你從Looper.myLooper()得到Looper,而不是從Context中得到 – pskink 2014-09-01 20:23:55

回答

0

我不明白你的問題,但我認爲我的回答清楚:

getActivity().getApplicationContext().getMainLooper().getThread()返回關聯到UI線程或等效主線程的線程。

Looper.getMainLooper().getThread()也返回上面的線程。所以他們倆居然一個對象,因此,如果條件爲真,這意味着:

「上下文線程IS應用程序的線程」

,如果你在主線程然後new Handler().getLooper().getThread()回報正上方線程。也Looper.getMainLooper().getThread()所以兩個refrences實際上指向一個對象,條件爲真,並

處理器線程IS主線程

您可以輕鬆地檢查這些if語句。 :-)

Why the following fails (both)?

不,我想你會感到困惑之外的意義。如果條件爲真且條件爲真,則拋出異常。這是不同的意思android的異常這是你的自定義一個,它會正確拋出,因爲條件滿足。