Service
What is a Service?
看看官方API的介绍!
What is a Service?
Most confusion about the Service class actually revolves around what it is not:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
服务既不是线程也不是进程,他是一个组件。一个应用程序一般只有一个进程,Service一般就是运行在此主进程的主线程里面(也可在清单文件使用android:process进行设置创建其它进程来运行)
Service的启动方式
service的启动方式有两种:
1.startService:
startService:
- 服务没有启动时会走 onCreate()–>onStartCommand()
(因为onStare()方法已经过时,所以不执行onStart()方法) - 服务已经启动: 此时只会走 onStartCommand() 方法
stopService:
- 停止服务会走 onDestroy() 方法;
2.bindService:
bindService:
- 假如服务没有启动时会走 onCreate()–>onBind–>onStartCommand()
(因为onStare()方法已经过时,所以不执行onStart()方法) - 假如服务已经启动: 会走 onBind() –> onStartCommand() 方法
unbindService:
- 解绑服务会走 onUnbind() –> onDestroy() 方法;
IntentService简介
- IntentService是Service的子类,比普通的Service增加了额外的功能
- 它会创建独立的worker线程来处理所有的Intent请求;
- 会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题;
- 所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service;
- 为Service的onBind()提供默认实现,返回null;
- 为Service的onStartCommand提供默认实现,将请求Intent添加到队列中;
服务通信
1、本地服务通信
本地服务通信是指应用程序内部的通信
在使用服务进行本地通信时,首先需要创建一个Service类,该类会提供一个IBind onBind()方法,onBind()方法的返回值IBinder对象会作用参数传递给ServiceConnection类中的onServiceConnection()方法,这样访问者就可以通过IBinder对象与Service进行通信。
2、远程服务通信
远程服务通信是指2个应用程序之间的通信(IPC)
在Android系统中,各个应用程序都运行在自己的进程中,进程之间一般无法直接进行通信,如果想完成不同进程之间的通信,就需要使用远程服务通信。
远程服务通信是通过AIDL(Android Interface Definition Language)实现的,它是一种接口定义语言,其语法格式类似于Java,但是存在几点不同:
1. AIDL定义接口的源代码必须以.aidl结尾
2. AIDL接口中用到的数据类型,除了基本类型,String,List,Map,CharSequence外,其它
类型全部都需要导入包,即使它们在同一个包中
3. AIDL定义接口时,里面的方法不用修饰符,默认是公开的,即去掉public
Service示例
start&stop Service
Intent intent = new Intent(this,TestService.class)
Context.startService(intent);//开启服务
Contxt.stopService(intent);//停止服务
绑定本地服务
MainActivity.java:
MyService.java
远程服务 与 绑定远程服务
调用者 MainActivity.java
服务提供者 :MusicService.java
IMusicService.aidl