单个服务的多个实例

Multiple instance of single service

假设我已经从后台的 activity 及其 运行 启动了一项服务,如果我再次启动该服务,那么该服务会重新启动还是会有多个实例?

参见 the docs 服务的生命周期:

There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called.

Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

基本上,它被创建一次(调用onCreate),并且对于每个后续调用startService,再次调用方法onStartCommand

服务器将决定是否调用onCreate本身,这取决于它是否已经运行ning。

if I start the service again then will the service restart

它不会重新创建或重新初始化自己,但是onStartCommand中的代码又是运行,所以一定要记住,你不要在那里做任何不应该发生的事情更多不止一次。在 onCreate.

中执行此操作