Android四大组件之Service(1)

1、Service概念、作用及特点

先看一下源码里对Service的解释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
* A Service is an application component representing either an application's desire
* to perform a longer-running operation while not interacting with the user
* or to supply functionality for other applications to use. Each service
* class must have a corresponding
* {@link android.R.styleable#AndroidManifestService <service>}
* declaration in its package's <code>AndroidManifest.xml</code>. Services
* can be started with
* {@link android.content.Context#startService Context.startService()} and
* {@link android.content.Context#bindService Context.bindService()}.
*
* <p>Note that services, like other application objects, run in the main
* thread of their hosting process. This means that, if your service is going
* to do any CPU intensive (such as MP3 playback) or blocking (such as
* networking) operations, it should spawn its own thread in which to do that
* work. More information on this can be found in
* <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
* Threads</a>. The {@link IntentService} class is available
* as a standard implementation of Service that has its own thread where it
* schedules its work to be done.</p>

从上边看出以下信息:

1
2
3
4
5
6
概念:服务为Android四大组件之一
作用:提供在后台需要长期运行的服务(如复杂计算、下载等等)
运行地方:在主线程中
注意事项:使用前必须在AndroidManifest.xml注册,如果要进行长期的运行需要自己的线程,即新建一个线程,也可以使用标准的IntentService。
启动方式:startService()和bindService()
特点:长生命周期的、没有用户界面、在后台运行

2、Service分类、各自特点及应用场景

Service分类
Service分类

3、Service与Thread的区别:

应该说Service和Thread没有任何联系,唯一相同点就是执行异步操作,由于Service有后台的概念,很容易将其和Thread混为一谈。一般来说,会将Service和Thread联合着用,即在Service中再创建一个子线程(工作线程)去处理耗时操作逻辑.

1
2
3
4
5
6
7
8
9
10
11
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//新建工作线程
new Thread(new Runnable() {
@Override
public void run() {
// 开始执行后台任务
}
}).start();
return super.onStartCommand(intent, flags, startId);
}

后台的定义:后台任务运行完全不依赖UI,即使Activity被销毁,或者程序被关闭,只要进程还在,后台任务就可以继续运行

4、Service生命周期

手动调用的方法:

手动调用的方法 作用 自动调用的内部方法
startService() 启动服务 onCreate()、onStartCommand()
stopService() 停止服务 onDestroy()
bindService() 绑定服务 onCreate()、onBind()
unbindService() 解绑服务 onUnBind()、 onDestroy()

内部自动调用的方法:

内部自动调用的方法 作用 说明
onCreate() 创建服务 首次创建服务时,系统将调用此方法来执行一次性设置程序(在调用onStartCommand() 或 onBind() 之前)。如果服务已在运行,则不会调用此方法。
onStartCommand() 开始服务 当另外一个组件(Activity)使用startService()启动服务的时候调用此方法。onStartCommmand()调用次数==启动次数,一旦执行此方法,服务即会启动并可在后台无限期运行。
onBind() 绑定服务 当另一个组件通过bindService()绑定服务时,系统会调用此方法,
onUnBind() 解绑服务 调用
onDestroy() 销毁服务 当服务不再使用且将被销毁时,系统将调用此方法。服务应该实现此方法来清理所有资源,如线程、注册的侦听器、接收器等。 这是服务接收的最后一个调用。

Service 两种形式

  • 启动状态
    当应用组件(例如Activity)通过startService()启动服务后,Service就处于启动状态,就会一直运行下去,除非手动调用stopServiec()
  • 绑定状态
    与启动服务不同的是绑定服务的生命周期通常只在为其他应用组件(如Activity)服务时处于活动状态,不会无限期在后台运行,也就是说宿主(如Activity)解除绑定后,绑定服务就会被销毁

此文章参考以下出处:
http://blog.csdn.net/javazejian/article/details/52709857
http://www.jianshu.com/p/d963c55c3ab9/