它取决于onStartCommand返回的值。
您必须返回START_NOT_STICKY
根据doc:
For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them
简而言之:
如果返回START_STICKY,只要资源可用,就会重新创建服务。如果您返回START_NOT_STICKY,则必须重新启用发送新意向的服务。
因为所有这一切触发了我的好奇心,我做了一个示例应用程序来测试这个。你可以找到所有的sources here的拉链
有一个startService按钮和stopService按钮,做你会期望从他们。
该服务在onStartCommand中返回START_NOT_STICKY。
我在onCreate,onStartCommand和onDestroy中放了敬酒。
这里会发生什么:
>如果我按开始,调用onCreate和onStart
>如果我按停止,onDestroy被触发
>如果我按两次启动,onCreate被调用一次和onStartCommand两次
所以它的行为正如人们所期望的。
如果我开始服务,杀死应用程序,如你所述,onDestroy不会被调用,但不是onCreate或onStart。
如果我回到应用程序,我再次按开始,onCreate被调用,这意味着,如我之前写的,START_NOT_STICKY阻止服务自动重新启动。
我想你的应用程序中有其他的东西,启动服务再次(也许一个挂起的意图)。