Android中的服务和windows中的服务是类似的东西,服务一般没有用户操作界面,它运行于系统中不容易被用户发觉,可以使用它开发如监控之类的程序 。
Service 的简单实用
- 第一步:继承Service类
public class MyService extends Service { }
- 第二步:在AndroidManifest.xml文件中的<application>节点里对服务进行配置:
<service android:name=".MyService" />
- 第三部:Service 启动方式
- 启动:Context.startService(Intent service)
- 停止:Context.stopService(Intent name)
- 启动:Context.bindService(Intent service, ServiceConnection conn,
int flags)- 停止:Context.unbindService(ServiceConnection conn)
Service 的两种启动方式
- 隐式启动:
首先在 AndroidManifest.xml 清单文件中对 service 进行配置:
<service android:name=".MyService" android:exported="true">
<intent-filter>
<action android:name="com.cfox.myservice"/>
</intent-filter>
</service>
从代码中可以看到在 service 中有 android:exported,并且我们设置成了 true ,如果设置成 true 则表示可以通过其他App 启动该服务,如果设置为false 不可被外部应用启动(默认为false),如果设置了 intent-filter 则android:exported将默认设置为true。再看这个几行配置代码,在service 中添加了 intent-filter ,又在 intent-filter 中添加 action。看到这可能会有疑问,action 是干什么的?下面我们来看一下隐式启动方式。
Intent intent = new Intent();
intent.setAction("com.cfox.myservice");
intent.setPackage("com.cfox.servicecontrol");
startService(intent);
我们可以看到在 Intent 中设置了 Action,并且 Action 的内容和 AndroidManifest.xml 中 intent-filter 中的 action 相对应。可到这里可能明白些了,继续看 setPackage 就又不明白了,启动service 为什么还要 setPackage ,在Android 5.0 开始如果你不设置 setPackage 将无法启动 service 同时还会抛出异常。下面我们来看一下 Android 4.4 和 Android 5.0 启动 service 的源码。
Android 4.4
@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service, mUser);
}
private ComponentName startServiceCommon(Intent service, UserHandle user) {
try {
validateServiceIntent(service);
.........//省略部分代码
} catch (RemoteException e) {
return null;
}
}
我们重点注意一下这代码:
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (true || getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.KITKAT) {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
//IllegalArgumentException ex = new IllegalArgumentException(
// "Service Intent must be explicit: " + service);
//Log.e(TAG, "This will become an error", ex);
//throw ex;
}
}
}
开到上面这段代码,就会明白,在 Android 4.4 中已经添加了这个安全机制,只是被注释了。
Android 5.0
其他地方都没有变,直接看Android 5.0 中 validateServiceIntent 方法:
private void validateServiceIntent(Intent service) {
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}
看到这段代码就知道在Android 5.0 以后为什么没有setPackage 会出现崩溃现象。
- service 显示启动:
下面是一种简单的显示启动方式:
Intent intent = new Intent(this,MyService.class);
startService(intent);
启动service 时可用通过 intent 设置数据。
Service 生命周期
下面我们来看一下集成 Service 类所有生命周期方法:
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
看完这些生命周期方法,可能已经有知道大概了。我service 的生命周期先介绍到这,下面结合启动方式在看一下service 的生命周期。
Service 的两种启动方式
- Context.startService()方法启动服务有关的生命周期方法
Service 的生命周期方法:onCreate() —> onStart() —> onStartCommand() —> onDestroy()- 注意:注意使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService。
- Context.bindService()方法启动服务有关的生命周期方法
Service 的生命周期方法:onCreate() —> onBind() —> onUnbind() —> onDestroy()。- 注意:你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自动解除,并且Service会自动停止)。
Service 生命周期方法
- onCreate()
该方法在服务被创建时调用,该方法只会被调用一次,无论调用多少次startService()或bindService()方法,服务也只被创建一次。
- onStartCommand()
在 sdk 2.0 及其以后的版本中,对应的 onStart 已经被弃用了,变为了onStartCommand,不过之前的 onStart 任然有效。这意味着,如果你开发的应用程序用的 sdk 为 2.0 及其以后的版本,那么你应当使用 onStartCommand 而不是 onStart。
- onBind()
只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。
- onUnbind()
该方法只有在调用 Context.bindService() 绑定服务后,在调用Context.unbindService() 解除绑定的时被调用 。
- onDestroy()
该方法在Service 销毁时被调用。但是如果这样----》设置-->下载-->强制停止。则不会执行ondestory方法,或者通过别人应用,如360直接kill掉我的应用时,也是不会调用Service的ondestory方法的。
被启动的服务的生命周期
如果一个Service被某个Activity 调用 Context.startService 方法启动,那么不管是否有Activity使用bindService绑定或unbindService解除绑定到该Service,该Service都在后台运行。如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStart将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,android系统也可能结束服务。
被绑定的服务的生命周期
如果一个Service被某个Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法都只会调用一次,同时onStart方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。
被启动又被绑定的服务的生命周期
如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate始终只会调用一次,对应startService调用多少次,Service的onStart便会调用多少次。调用unbindService将不会停止Service,而必须调用 stopService 或 Service的 stopSelf 来停止服务。
- 注意:同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止。
让Service自动重启而不被kill掉
先让我们看一下 Service 重启方法,很简单,只要重写service的onStartCommand方法。根据实际设置返回值就可以了。
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
下面我们介绍下这个方法,在Android开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一个int的返回值,这篇文章就是简单地讲讲int返回值的作用。
从Android官方文档中,我们知道onStartCommand有4种返回值:
- START_STICKY:
如果service进程被kill掉,保留service的状态为。
开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
- START_NOT_STICKY:
“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
- START_REDELIVER_INTENT:
重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
- START_STICKY_COMPATIBILITY:
START_STICKY的兼容版本,但不保证服务被kill后一定能重启。
在 AndroidManifest.xml 里 Service 元素的常见选项
key | value |
---|---|
android:name | 服务类名 |
android:label | 服务的名字,如果此项不设置,那么默认显示的服务名则为类名 |
android:icon | 服务的图标 |
android:permission | 服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务 |
android:process | 表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字 |
android:enabled | 如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false |
android:exported | 表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false |
bindService 启动 Service 方法:
定义服务实现效接口:
public interface IServiceControl {
void insert(String msg);
void addList(List<String> lists);
String query(String id);
UserInfo setUser(UserInfo userInfo);
}
UserInfo 类:
public class UserInfo {
private String name;
private int age;
public UserInfo(){}
public UserInfo(String name,int age){
this.name = name;
this.age = age;
}
..... get and set method ....
}
service 中 IBinder 接口的实现:
创建类继承 Binder 并实现 IServiceControl 接口。
private class MyBind extends Binder implements IServiceControl{
@Override
public void insert(String msg) {
}
@Override
public void addList(List<String> lists) {
}
@Override
public String query(String id) {
return "return String message";
}
@Override
public UserInfo setUser(UserInfo userInfo) {
return userInfo;
}
}
启动Service 中 Activity 中 ServiceConnection 的使用
在使用 Context.bindService 启动服务时,要实现ServiceConnection 接口。
private IServiceControl serviceControl;
private class MyControl implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceControl = (IServiceControl) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceControl = null;
}
}
在activity 中启动 Service
Intent intent = new Intent(this, InService.class);
MyControl conn = new MyControl();
bindService(intent,conn, BIND_AUTO_CREATE);
方法的调用
通过 serviceControl 调用 Service 中的实现方法。