获取服务中的上下文
有没有可靠的方法从 Service
获取 Context
?
我想为 ACTION_PHONE_STATE_CHANGED
注册广播接收器,但我不需要我的应用始终获取此信息,因此我没有将其放入 Manifest
中。
但是,当我需要此信息时,我不能让广播接收器被 GC 终止,因此我在 Service
中注册广播接收器。
因此,我需要一个Context
来调用registerReceiver()
。 当我不再需要ACTION_PHONE_STATE_CHANGED
时,我取消注册它。
有什么建议吗?
Is there any reliable way to get a Context
from a Service
?
I want to register a broadcast receiver for ACTION_PHONE_STATE_CHANGED
but I don't need my app to always get this information, so I don't put it in the Manifest
.
However, I can't have the broadcast receiver be killed by the GC when I need this information so I'm registering the broadcast receiver in a Service
.
Hence, I need a Context
to to call registerReceiver()
.
When I no longer need the ACTION_PHONE_STATE_CHANGED
I unregister it.
Any tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
服务 是一个 上下文
Service is a Context
Service
扩展了ContextWrapper
,而ContextWrapper又扩展了
Context
。因此,Service
是一个Context
。在服务中使用
'this'
关键字。Service
extendsContextWrapper
which extendsContext
. Hence theService
is aContext
.Use
'this'
keyword in the service.Service
扩展ContextWrapper
ContextWrapper
扩展Context
所以......
(在服务或活动类中)
Service
extendsContextWrapper
ContextWrapper
extendsContext
So....
(in Service or Activity Class)
以防万一有人遇到
NullPointerException
,您需要在onCreate() 中获取上下文。
Service
是一个Context
>,所以这样做:注意:
阅读:“不要将 Android 上下文类放在静态字段中;这是内存泄漏(并且也会破坏即时运行)” 你知道上下文类是什么吗? Activity 就是其中之一,您不应该将 Activity 存储为静态字段(否则会泄漏内存)。但是,您可以将 Context(只要它是应用程序上下文)存储为静态字段,因为它的寿命比所有内容都长。
just in case someone is getting
NullPointerException
, you need to get the context insideonCreate().
Service
is aContext
, so do this:Note:
Read: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" Do you know what context classes are? Activity is one of them, and you should not store Activity as a static field, (or it will leak memory). However, you can store Context (as long as it is the application context) as a static field, since it outlives everything.
由于
Service
是一个Context
,因此变量 context 必须是this
:Since
Service
is aContext
, the variable context must bethis
:由于服务本身已经是上下文,
您甚至可以通过以下方式获取它:
或
As Service is already a Context itself
you can even get it through:
OR
如果您需要服务上下文,请使用
this
关键字。如果您想要活动上下文,您可以通过在活动
onCreate()
中创建静态变量来访问它,现在您可以在服务内访问该上下文
If you want service context then use
this
keyword. if you want activity context you can access that by using by making static variable like thisin the activity
onCreate()
now you can access that context inside the service