如果多次启动Android服务会怎样?


119

如果我有以下代码:

Intent intent = new Intent(this,DownloadService.class);     
for(int i=0;i<filesArray.length;i++){        
     startService(intent);          
}

在此代码中DownloadService扩展IntentService

因此,现在当我打电话时startService(intent),这意味着我每次都在启动一个新服务,startService(intent)或者这意味着它DownloadService要运行一次,然后每次我调用startService(intent)它时,都会传递具有不同startId的不同意图。

这有意义吗?是哪种情况?

Answers:


166

该服务将仅在一个实例中运行。但是,每次启动服务时,onStartCommand()都会调用该方法。

这是记录在这里


1
谢谢。那里也说:“ startService()方法立即返回,Android系统调用该服务的onStartCommand()方法。如果该服务尚未运行,则系统首先调用onCreate(),然后调用onStartCommand()。” 因此,如果服务已经在运行,那么系统将跳过onCreate()方法,仅调用onStartCommand()或什么?
bytebiscuit 2011年

我真的不知道,但是我很确定是这种情况(onCreate()如果已经创建了服务,那么就不要打了很多电话)。确定是否Log.i()在两个回调中都放入a 并检查LogCat 应该很容易。
菲利普·温特

只是这样做...而且很奇怪,它在最后一次startService()调用之后启动了onCreate!
bytebiscuit 2011年

15
那是因为startService()是异步的。因此,当您循环调用时,服务本身尚未获得任何资源,也尚未启动。
菲利普·温特

1
@neelabh不是“立即”,它需要一些时间来启动服务,并且“ for”循环仍将运行,并一次又一次地调用该服务,因此第一次尝试将找不到任何正在运行的服务...因此,方法startService()将被调用两次,直到服务启动完成。请原谅我的英语不好。
mzalazar

21

完全正确。仅为一个应用程序进程创建Service的一个实例。当您StartService();再次调用时,只有onStartCommand()被调用,并且新的Intent会传递给onStartCommand()方法。

注意: onCreate()不再调用。

关于bindService()多次通话:

当您bindService()多次调用时,再次只有一个实例用于Service,Android Runtime将相同的IBinder对象返回给客户端。

意思onBind()是,不叫多次。并返回刚刚缓存的IBinder对象。


是否onStop()必须为每个对应项调用onStartCommand
IgorGanapolsky '16

6
@IgorGanapolsky:首先,Service中没有这样的回调方法onStop()。我们需要调用stopService()或stopSelf()来停止服务。当多次针对多个意图调用onStartCommand()时,我们仅需要调用一次stopSelf()或stopService()。如果使用IntentService,则应调用stopSelfResult(int id),以从onHandleIntent()传递请求的起始ID,这将停止放置在IntentService工作队列中的相应起始ID请求。希望这可以帮助。
阿尼什米塔尔

8

在上述答案中添加更多信息可能对其他答案有所帮助,startIdonStartCommand()每次startService()调用所接收的方法都不同。

同样,如果我们如上所述编写for循环,则写入的代码onHandleIntent()将按for循环频率定义执行多次,但是顺序执行而不是并行执行。

这个概念是IntentService创建一个工作队列,并startService()触发每个请求onStartCommand(),然后依次将意图存储在工作队列中,然后将意图一一传递给onHandleIntent()


2

根据文档

startService()方法立即返回,并且Android系统调用服务的onStartCommand()方法。如果该服务尚未运行,则系统首先调用onCreate(),然后调用onStartCommand()。

启动服务的多个请求导致对该服务的onStartCommand()的多个相应调用。但是,仅需要一个停止服务的请求(使用stopSelf()或stopService())即可停止该服务。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.