2010-07-12 75 views
28

AccountAuthenticator.java:如何從意圖獲取上下文?

Intent intent = new Intent(context, AccountActivity.class); 

AccountActivity.java:
在的onCreate(捆綁aBundle)我想說:

getIntent().getContext(); 

不過的getContext()不存在。

如何從意圖獲取上下文?
由於它在Intent構造函數中傳遞,我期待它在到達AccountActivity時可用。

+0

爲什麼你需要從意圖上下文? – Maragues 2010-07-12 10:55:35

+0

我需要創建Intent的Service(即Context),以便能夠在構造函數中創建一個AsyncTask。如果我不這樣做,我會得到:「java.lang.SecurityException:調用者uid 10027與認證者的uid不同」,因爲AsyncTask正在執行Accountmanager am = Accountmanager.get(context)。 – user77115 2010-07-12 11:00:19

+0

對於我來說,我試圖使用TDD並驗證正在測試的代碼中設置了正確的上下文。 – PseudoNoise 2013-06-05 18:47:10

回答

32

如何從 意圖獲取上下文?

你不知道。

,因爲它是在Intent 構造過去了,我期待它是可以用在 AccountActivity到來 。

Context僅用於幫助創建路由信息Intent。由於Intent可以(且經常)生活在任何Context之外,所以Intent不能容納在Context之上。

我需要的服務(即上下文),其 創建的意圖,以便能夠 創建的AsyncTask把它在 構造。

你不能這樣做,對不起。

如果我不這樣做,我得到: 「java.lang.SecurityException異常:主叫 UID 10027比 認證的UID不同」,因爲 的AsyncTask是幹什麼的AccountManager AM = Accountmanager.get (上下文)。

這與AsyncTask無關。這與進程有關,而不是線程。

+0

完美的解釋。榮譽:) CommonsWare – 2017-06-23 05:43:56