Service

引入目的:在用户没有同app交互时可运行在后台;如果目的是在交互时不打断main thread可以使用thread,分两种:

1、startService(intent):app结束后也可运行。通常执行单个操作、不返回结果。实现onStartCommand()。stopSelf()、stopService()停止。

2、bindService():所有绑定的app unbind后,service被销毁;可C-S模式的IPC,跨进程通信--发送请求、获取结果。实现onBind(),返回IBinder用于与C端交互。

3、service在main thread中运行,需执行耗时操作应该创建新thread。

4、生命周期:

  onCreate():第一次调用。

  onStartCommand()、onBind():启动、绑定服务时调用,被系统kill恢复时调用。可被多次调用。

  onDestroy():销毁调用。startedService调用一次stopSelf()、stopService()停止。boundServie全部unbindService()后调用。

5、实现startedService:

  继承原始Service类:灵活,通常需自己新建thread。

  继承IntentService类:onHandleIntent()中使用worker thread顺序处理所有Intent。

  获取service结果:使用PendingIntent、getBroadcast(),service使用broadcast提供结果。

6、创建boundService:

  目的:作为其它组件的一部分。

7、通知用户:Toast、状态栏

8、service前端运行:startForeground(状态栏通知),不易被系统kill

原文地址:https://www.cnblogs.com/toven/p/2609717.html