Service 的两种使用场景:
a: 在后台长时间运行的任务,不需要UI
b: 为其他App 提供通信接口,实现跨进程通信功能Service定义为后台,与我们说的启动一个异步后台任务不是一个概念,Service 的运行是在主线程中,如果在Service 中有耗时的任务,需要启动线程去处理。 这里的后台更多的是与Activity对比:Service 和Activity 都是Android 的基本组件,都被系统统一管理,有其对应的生命周期,Activity 是UI层,负责与用户交互,而Service是运行在后台没有UI的一个组件。
Service 被系统Kill 后,是否重启以及重启后的行为,根据onStartCommand 的返回值,可以分为以下三种情况:
a: START_NOT_STICKY:do not recreate the service unless there are pending intents
to deliver
b: START_STICKY: recreate the service and call [onStartCommand()], but do
not redeliver the last intent. Instead, the system calls onStartCommand() with a null
intent unless there are pending intents to start the service. 适用于类似后台播放音
乐的Service: 等待命令发送并执行相关任务
c: START_REDELIVER_INTENT: recreate the service and call onStartCommand()
with the last intent that was delivered to the service. 适用于专门执行某种任务并且要
求及时更新需求的的Service: 例如下载文件启动Service 有两种方式:startService 和bindService
实现Service 的三种方法:
a: 采用实现binder 的方法: 适用于同一个进程中其他组件对Service 的使用
b: 采用Messager 的方法:实现了跨进程访问,不过Service 是串行的处理Client 端的请
求
c: 采用AIDL的方法: 实现跨进程访问,并且Service 是并行的处理Client端的请求;
Service要处理线程安全相关的问题
参考链接:
1.https://developer.android.com/guide/components/services.html
2.https://developer.android.com/guide/components/bound-services.html#Lifecycle
Service 基础知识总结
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 上篇我们讲解了Android中的5中等级的进程,分别是:前台进程、可见进程、服务进程、后台进程、空进程。系统会按照...
- 1.什么是Activity?问的不太多,说点有深度的 四大组件之一,一般的,一个用户交互界面对应一个activit...
- 最近刚从旧公司离职,为面试在做准备,因为平时开发CV大法用得比较多,很多基础知识掌握得不是很牢靠以及很多工具框架只...