Service作为几大组件之一使用非常频繁,也有一些相对深入的知识点,但是也有很多比较浅显的特性,却与我们更加息息相关,记住这些特性,性价比极高。
- 通过
bindService方式启动的Service通过同样数量的unbindService可以关闭,且每一个调用了bindService的Context需要分别调用unbindService
- 通过
startService启动的Service经过同样数量的bindService和unbindService之后,仍然需要通过stopService关闭。如果提前调用stopService也关闭不掉,需要与bindService相同数量的unbindService被调用后,之前调用的stopService才会生效,此时Service才会关闭
- 在同一个
Context下bindService多次,实际上只相当于bind了一次,可通过一次unbindService就关闭
bindService尽量在Activity的Context下调用,不要在Application的Context下调用
startService与stopService在Application或者Activity的Context下都一样
- 多个
Context对同一个Service调用bindService,该Service只会在第一次bind的时候回调onBind,之后的bind不会回调。
- 通过
startService方式启动的Service,如果在onUnbind中return true,那么在全部Context解绑后但是还没有调用stopService或者stopSelf来关闭时,此时Service依然在运行,下次再有Context来bind的时候,会回调onRebind(见下图)。

参考文献
https://developer.android.com/guide/components/bound-services#Basics