Android 四大组件之 Service

本地服务

调用者和 Service 在同一个进程里,所以运行在主进程的 main 线程中。所以不能进行耗时操作,可以采用在 Service 里面创建一个 Thread 来执行任务。
任何 Activity 都可以控制同一个 Service,而系统也只会创建一个对应 Service 的实例。

启动方式

1、通过 start 方式开启服务

步骤:
1,定义一个类继承 Service;
2,清单文件中注册 Service;(必须)
3,使用 Context 的 startService(Intent) 方法启动服务;
4,不再使用时,记得调用 stopService(Intent) 方法停止服务。

生命周期:
onCreate() -- > onStartCommand() -- > onDestory()
注意:如果服务已经开启,不会重复回调 onCreate() 方法。如果再次调用 context.startService() 方法,Service 会调用 onStart() 或者 onStartCommand() 方法。停止服务需要调用context.stopService() 方法,服务停止的时候回调 onDestory() 被销毁。

特点:
一旦服务开启就跟调用者没有任何关系了。调用者退出了,调用者挂了,服务还在后台长期的运行,调用者不能调用服务里面的方法。

2、通过 bind 方式开启服务

步骤:
1,定义一个类继承 Service ;
2,在清单文件中注册 Service ;(必须)
3,使用 context 的 bindService(Intent,ServiceConnection,int) 方法启动服务;
4,不再使用时,调用 unBindService(ServiceConnection) 方法停止该服务。

生命周期:
onCreate() -- > onBind() --> onUnbind() -- > onDestory()
注意:绑定服务不会调用 onStart() 或者 onStartCommand() 方法

特点:bind 的方式开启服务,绑定服务,绑定者挂了,服务也会跟着挂掉。绑定者可以调用服务里面的方法。

远程服务

调用者和 Service 不在同一个进程中,Service 在单独的进程中的 main 线程,是一种跨进程通信方式。参考

如何保证 Service 不被杀死?

  1. 在 onStartCommand() 中返回 START_STICKY;
  2. 提升 Service 的优先级,在 Service 中创建一个 Notification,这样 service 就是前台的进程了;
  3. 在 onDestory() 中发送广播,来重新开启。

IntentService

IntentService 是 Service 的子类,比普通的 Service 增加了额外的功能。
特征:

  • 会创建独立的 worker 线程来处理所有的 Intent 请求;
  • 会创建独立的 worker 线程来处理 onHandleIntent() 方法实现的代码,无需处理多线程问题;
  • 所有请求处理完成后,IntentService 会自动停止,无需调用 stopSelf() 方法停止 Service;
  • 为 Service 的 onBind() 提供默认实现,返回null;
  • 为 Service 的 onStartCommand() 提供默认实现,将请求 Intent 添加到队列中;

你可能感兴趣的:(Android 四大组件之 Service)