Android Service stopSelf

在开发的过程,用到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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容