Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Android Service #48

Open
yunshuipiao opened this issue May 27, 2019 · 0 comments
Open

Android Service #48

yunshuipiao opened this issue May 27, 2019 · 0 comments
Labels

Comments

@yunshuipiao
Copy link
Owner

Android Service

[TOC]

Service 分为两种工作状态:

  • 启动状态:主要用于执行后台计算
  • 绑定状态:主要用于其他组件和 Service 的交互

两种状态可以并存。

生命周期

  • onCreate:首次创建服务时,系统调用次方法;如果服务正在运行,则不会调用,只会执行一次。
  • onStartCommand:但另一个组件调用 startService() 请求启动服务时,系统调用
  • onBind:另一个组件通过调用 bindService() 与服务绑定时,系统将调用此方法
  • onUnBind:另一个组件调用 unBindService() 与服务解绑,系统将调用此方法。
  • onRebind:当旧服务解绑,新组组件和服务绑定时,系统调用。
  • onDestory:当服务不在使用且被销毁时,系统调用此方法

启动方式

上面的生命周期我们可知道,启动 Service 的方式有两种分别是 startService 和 bindService,接下来我们来分别介绍一下

Service 通信

Activity 与 Service 进行通信有四种方式

  • 通过 Intent 传递参数

  • Binder 类:创建一个 Binder 类,让其实现 android.os.Binder 类,并且定义一个方法 setData,然后我们通过 onBind()方法将其对象返回 MainActivity。

  • 接口回调 CallBack 在 MyService 设置 CallBack

  • 使用 广播

IntentService

IntentService 是继承并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作,启动 IntentService 的方式和启动传统的 Service 一样,同时,当任务执行完后,IntentService 会自动停止,而不需要我们手动去控制或 stopSelf()。另外,可以启动 IntentService 多次,而每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。

ForegroundService

ForegroundService 前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除

应用场景:在一般情况下,Service 几乎都是在后台运行,一直默默地做着辛苦的工作。但这种情况下,后台运行的 Service 系统优先级相对较低,当系统内存不足时,在后台运行的 Service 就有可能被回收。 那么,如果我们希望 Service 可以一直保持运行状态且不会在内存不足的情况下被回收时,可以选择将需要保持运行的 Service 设置为前台服务。

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant