美文网首页
Android Service stopSelf

Android Service stopSelf

作者: 心无杂念的小屋 | 来源:发表于2017-07-06 10:14 被阅读0次

在开发的过程,用到service,下面来了解下stopSelf(int startId)和stopSelf的区别

如果Service之前没有启动,那么第一次会调用onCreate函数,然后会调用onStartCommand(Intent intent,int flags,int startId),这里的startId和stopSelf(int startId)里的参数是一一对应的,如果stopSlef(int startId)后,如果onStartCommand成对称调用后,serivce就会被销毁(onDestroy()函数会被调用),否则service一直是处于运行状态的

onStartCommand(..., 1)

onStartCommand(..., 2)

onStartCommand(..., 3)

stopSelf(1)

stopSelf(2)

stopSelf(3)

service.onDestroy(), // 在调用stop(int startId)的过程中,系统会检测是否还有startId存在,如果存在,则不销毁service,否则销毁service,当onStartCommand和它成对的时候,service才会被销毁,当然如果你直接调用stopSelf(-1),那么将直接销毁service,系统就不会检测是否还有其他的startId存在

而stopSelf()则会立即销毁service(onDestroy()函数会被立即执行),service的生命周期结束,从源码里可以看出stopSelf()里面是调用的stopSelf(-1),系统是根据这个字段来销毁service的,

stopService和stopSelf()的结果是一样的,都会立即销毁service

相关文章

网友评论

      本文标题:Android Service stopSelf

      本文链接:https://www.haomeiwen.com/subject/igthhxtx.html