Android 如何从 Intent 获取上下文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3227670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the Context from the Intent?
提问by user77115
AccountAuthenticator.java:
AccountAuthenticator.java:
Intent intent = new Intent(context, AccountActivity.class);
AccountActivity.java:
In onCreate(Bundle aBundle) I want to say:
AccountActivity.java:
在onCreate(Bundle aBundle)中我想说:
getIntent().getContext();
But getContext() does not exist.
但是 getContext() 不存在。
How do I get the Context from the Intent ?
Since it's passed in the Intent constructor, I was expecting it to be available on arrival in the AccountActivity.
如何从 Intent 获取上下文?
因为它是在 Intent 构造函数中传递的,所以我希望它在到达 AccountActivity 时可用。
回答by CommonsWare
How do I get the Context from the Intent ?
如何从 Intent 获取上下文?
You don't.
你没有。
Since it's passed in the Intent constructor, I was expecting it to be available on arrival in the AccountActivity.
因为它是在 Intent 构造函数中传递的,所以我希望它在到达 AccountActivity 时可用。
The Context
is only used to help create the Intent
routing information. Since an Intent
can (and frequently does) live outside of any Context
, an Intent
cannot hold onto a Context
.
将Context
仅用于帮助创建Intent
路由信息。由于Intent
can(并且经常确实)存在于 any 之外Context
,因此 anIntent
无法保留Context
.
I need the Service (i.e. Context) that created the Intent, so as to be able to create an AsyncTask taking it in the constructor.
我需要创建意图的服务(即上下文),以便能够在构造函数中创建一个 AsyncTask。
You cannot do this, sorry.
你不能这样做,对不起。
If I don't do that I get: "java.lang.SecurityException: caller uid 10027 is different than the authenticator's uid", since the AsyncTask is doing Accountmanager am = Accountmanager.get(context).
如果我不这样做,我会得到:“java.lang.SecurityException: caller uid 10027 is different than the authenticationator's uid”,因为 AsyncTask 正在做 Accountmanager am = Accountmanager.get(context)。
This has nothing to do with AsyncTask
. This has to do with processes, not threads.
这与AsyncTask
. 这与进程有关,而不是线程。