我应该在服务中使用哪个上下文?

Which context should i use in a service?

我的应用程序中有两项服务 - lA_svclB_svc

MainActivity 启动 lA_svc - 我应该使用哪个 context 从 activity 启动服务?

现在 lA_svc 发送启动 lB_svc 的意图 - 我应该在 startService() 方法中使用哪个 context

过了一会儿,lB_svc 发送一个 intent 来启动 lA_svc,我在这里使用哪个 context

能否请您link任何要点、示例来理解要启动服务的上下文?

which context should I use for launching the service from the activity?

A Service 可以从每个组件启动。由于您在 Activity 中,我假设您可以访问两个 Context:

  • Activity 上下文
  • 应用程序上下文

你使用哪一个并不重要,但对我来说更有意义的是,使用你的封闭组件之一,所以 Activity 上下文(使用 this)。

Now lA_svc sends an intent to launch lB_svc. - which context should I use here in the startService() method?

同样,您可以从每个组件启动服务,再次使用封闭组件的 Context 是有意义的,因此 Service 上下文(只需使用 this 在您的服务中)。

After a while, lB_svc sends an intent to launch lA_svc, which context do I use here?

这里的问题是一样的:你想从另一个 Service 开始一个 Service。因此,只需使用您的 Service 上下文即可。

我读过的关于 Context 的最好的文章是来自 Dave Smith 的 this

基本上您的 Activity 和服务都是上下文。启动服务时,使用哪个上下文并不重要。使用你 Activity/Service 甚至应用程序上下文。

Here's 一篇很好的文章,说明了何时使用哪个上下文很重要。