如果多次启动服务会发生什么?

byt*_*uit 111 android

如果我有以下代码:

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

在此代码中DownloadService扩展IntentService.

所以现在,当我打电话时startService(intent),这意味着每次调用我都会启动一项新服务,startService(intent)或者这意味着它DownloadService会运行一次,然后每次调用startService(intent)它时,只会使用不同的startId传递不同的意图.

这是否有意义,以及其中哪一个是这样的?

Phi*_*ndt 160

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

在此处记录

  • 那是因为`startService()`是异步的.因此,当您循环调用时,服务本身没有获得任何资源,也没有启动. (15认同)

Ani*_*tal 16

完全正确.仅为应用程序进程创建一个Service实例.当你调用onStart(); 再次,然后只调用onStartCommand()并将新的Intent传递给onStartCommand()方法.

注意:不再调用onCreate().

关于多次调用bindService():

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

意味着,onBind()不会被多次调用.并且只返回缓存的IBinder对象.

  • @IgorGanapolsky:首先,Service中没有onStop()的回调方法.我们需要调用stopService()或stopSelf()来停止服务.当多个意图多次调用onStartCommand()时,我们只需调用一次stopSelf()或stopService().如果使用IntentService,则应该调用stopSelfResult(int id)从onHandleIntent()传递请求的start id,这将停止相应的start id请求,该请求放在IntentService的工作队列中.希望这可以帮助. (6认同)

Rah*_*pta 5

在上述答案中添加一些可能对其他人有帮助的信息是,startIdonStartCommand()方法接收的每个startService()呼叫都是不同的.

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

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