欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中的Service相关全面总结

程序员文章站 2023-12-02 18:40:34
1、service的种类 按运行地点分类: 类别 区别  优点 缺点   应用 本地服务(local) 该服务...
1、service的种类
按运行地点分类:
类别 区别  优点 缺点   应用
本地服务(local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外local服务因为是在同一进程因此不需要ipc,也不需要aidl。相应bindservice会方便很多。  主进程被kill后,服务便会终止。  非常常见的应用如:htc的音乐播放服务,天天动听音乐播放服务。
远程服务(remote) 该服务是独立的进程,  服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在activity所在进程被kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。  该服务是独立的进程,会占用一定资源,并且使用aidl进行ipc稍微麻烦一点。  一些提供系统服务的service,这种service是常驻的。

其实remote服务还是很少见的,并且一般都是系统服务。
按运行类型分类:
类别 区别 应用
前台服务 会在通知一栏显示 ongoing 的 notification, 当服务被终止的时候,通知一栏的 notification 也会消失,这样对于用户有一定的通知作用。常见的如音乐播放服务。
后台服务 默认的服务即为后台服务,即不会在通知一栏显示 ongoing 的 notification。 当服务被终止的时候,用户是看不到效果的。某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等。

有同学可能会问,后台服务我们可以自己创建 ongoing 的 notification 这样就成为前台服务吗?答案是否定的,前台服务是在做了上述工作之后需要调用 startforeground ( android 2.0 及其以后版本 )或 setforeground (android 2.0 以前的版本)使服务成为 前台服务。这样做的好处在于,当服务被外部强制终止掉的时候,ongoing 的 notification 任然会移除掉。
按使用方式分类:
类别 区别
startservice 启动的服务 主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopservice
bindservice 启动的服务 该方法启动的服务要进行通信。停止服务使用unbindservice
startservice 同时也 bindservice 启动的服务 停止服务应同时使用stepservice与unbindservice

以上面三种方式启动的服务其生命周期也有区别,将在随后给出。
2、service 与 thread 的区别
很多时候,你可能会问,为什么要用 service,而不用 thread 呢,因为用 thread 是很方便的,比起 service 也方便多了,下面我详细的来解释一下。
1). thread:thread 是程序执行的最小单元,它是分配cpu的基本单位。可以用 thread 来执行一些异步的操作。
2). service:service 是android的一种机制,当它运行的时候如果是local service,那么对应的 service 是运行在主进程的 main 线程上的。如:oncreate,onstart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是remote service,那么对应的 service 则是运行在独立进程的 main 线程上。因此请不要把 service 理解成线程,它跟线程半毛钱的关系都没有!

既然这样,那么我们为什么要用 service 呢?其实这跟 android 的系统机制有关,我们先拿 thread 来说。thread 的运行是独立于 activity 的,也就是说当一个 activity 被 finish 之后,如果你没有主动停止 thread 或者 thread 里的 run 方法没有执行完毕的话,thread 也会一直执行。因此这里会出现一个问题:当 activity 被 finish 之后,你不再持有该 thread 的引用。另一方面,你没有办法在不同的 activity 中对同一 thread 进行控制。

举个例子:如果你的 thread 需要不停地隔一段时间就要连接服务器做某种同步的话,该 thread 需要在 activity 没有start的时候也在运行。这个时候当你 start 一个 activity 就没有办法在该 activity 里面控制之前创建的 thread。因此你便需要创建并启动一个 service ,在 service 里面创建、运行并控制该 thread,这样便解决了该问题(因为任何 activity 都可以控制同一 service,而系统也只会创建一个对应 service 的实例)。

因此你可以把 service 想象成一种消息服务,而你可以在任何有 context 的地方调用 context.startservice、context.stopservice、context.bindservice,context.unbindservice,来控制它,你也可以在 service 里注册 broadcastreceiver,在其他地方通过发送 broadcast 来控制它,当然这些都是 thread 做不到的。
3、service的生命周期
oncreate  onstart  ondestroy  onbind
1). 被启动的服务的生命周期:如果一个service被某个activity 调用 context.startservice 方法启动,那么不管是否有activity使用bindservice绑定或unbindservice解除绑定到该service,该service都在后台运行。如果一个service被startservice 方法多次启动,那么oncreate方法只会调用一次,onstart将会被调用多次(对应调用startservice的次数),并且系统只会创建service的一个实例(因此你应该知道只需要一次stopservice调用)。该service将会一直在后台运行,而不管对应程序的activity是否在运行,直到被调用stopservice,或自身的stopself方法。当然如果系统资源不足,android系统也可能结束服务。

2). 被绑定的服务的生命周期:如果一个service被某个activity 调用 context.bindservice 方法绑定启动,不管调用 bindservice 调用几次,oncreate方法都只会调用一次,同时onstart方法始终不会被调用。当连接建立之后,service将会一直运行,除非调用context.unbindservice 断开连接或者之前调用bindservice 的 context 不存在了(如activity被finish的时候),系统将会自动停止service,对应ondestroy将被调用。

3). 被启动又被绑定的服务的生命周期:如果一个service又被启动又被绑定,则该service将会一直在后台运行。并且不管如何调用,oncreate始终只会调用一次,对应startservice调用多少次,service的onstart便会调用多少次。调用unbindservice将不会停止service,而必须调用 stopservice 或 service的 stopself 来停止服务。

4). 当服务被停止时清除服务:当一个service被终止(1、调用stopservice;2、调用stopself;3、不再有绑定的连接(没有被启动))时,ondestroy方法将会被调用,在这里你应当做一些清除工作,如停止在service中创建并运行的线程。
特别注意
1、你应当知道在调用 bindservice 绑定到service的时候,你就应当保证在某处调用 unbindservice 解除绑定(尽管 activity 被 finish 的时候绑定会自      动解除,并且service会自动停止);
2、你应当注意 使用 startservice 启动服务之后,一定要使用 stopservice停止服务,不管你是否使用bindservice;
3、同时使用 startservice 与 bindservice 要注意到,service 的终止,需要unbindservice与stopservice同时调用,才能终止 service,不管 startservice 与 bindservice 的调用顺序,如果先调用 unbindservice 此时服务不会自动终止,再调用 stopservice 之后服务才会停止,如果先调用 stopservice 此时服务也不会终止,而再调用 unbindservice 或者 之前调用 bindservice 的 context 不存在了(如activity 被 finish 的时候)之后服务才会自动停止;
4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 activity 如果会自动旋转的话,旋转其实是 activity 的重新创建,因此旋转之前的使用 bindservice 建立的连接便会断开(context 不存在了),对应服务的生命周期与上述相同。
5、在 sdk 2.0 及其以后的版本中,对应的 onstart 已经被否决变为了 onstartcommand,不过之前的 onstart 任然有效。这意味着,如果你开发的应用程序用的 sdk 为 2.0 及其以后的版本,那么你应当使用 onstartcommand 而不是 onstart。
4、startservice 启动服务
想要用 startservice 启动服务,不管local 还是 remote 我们需要做的工作都是一样简单。当然要记得在 androidmanifest.xml 中注册 service。
根据上面的生命周期,我们便会给出 service 中的代码框架:
复制代码 代码如下:

package com.newcj.test;
import android.app.service;
import android.content.intent;
import android.os.ibinder;
public class localservice1 extends service {
/**
* onbind 是 service 的虚方法,因此我们不得不实现它。
* 返回 null,表示客服端不能建立到此服务的连接。
*/
@override
public ibinder onbind(intent intent) {
return null;
}
@override
public void oncreate() {
super.oncreate();
}
@override
public void onstart(intent intent, int startid) {
super.onstart(intent, startid);
}
@override
public void ondestroy() {
super.ondestroy();
}
}

复制代码 代码如下:

// 启动一个 activity
startactivity(new intent(this, localservice1.class));
...
// 停止一个 activity
stopservice(new intent(this, localservice1.class));

对应的 intent 为标志服务类的 intent。
5、local 与 remote 服务绑定
同样记得在 androidmanifest.xml 中注册 service
1). local 服务绑定:local 服务的绑定较简单,首先在 service 中我们需要实现 service 的抽象方法 onbind,并返回一个实现 ibinder 接口的对象。
service 中的代码:
复制代码 代码如下:

package com.newcj.test;
import android.app.service;
import android.content.intent;
import android.os.binder;
import android.os.ibinder;
public class localservice extends service {
/**
* 在 local service 中我们直接继承 binder 而不是 ibinder,因为 binder 实现了 ibinder 接口,这样我们可以少做很多工作。
* @author newcj
*/
public class simplebinder extends binder{
/**
* 获取 service 实例
* @return
*/
public localservice getservice(){
return localservice.this;
}
public int add(int a, int b){
return a + b;
}
}
public simplebinder sbinder;
@override
public void oncreate() {
super.oncreate();
// 创建 simplebinder
sbinder = new simplebinder();
}
@override
public ibinder onbind(intent intent) {
// 返回 simplebinder 对象
return sbinder;
}
}

上面的代码关键之处,在于 onbind(intent) 这个方法 返回了一个实现了 ibinder 接口的对象,这个对象将用于绑定service 的 activity 与 local service 通信。下面是 activity 中的代码:
复制代码 代码如下:

package com.newcj.test;
import android.app.activity;
import android.content.componentname;
import android.content.context;
import android.content.intent;
import android.content.serviceconnection;
import android.os.bundle;
import android.os.ibinder;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
public class main extends activity {
private final static string tag = "service_test";
private serviceconnection sc;
private boolean isbind;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
sc = new serviceconnection() {
@override
public void onservicedisconnected(componentname name) {
}
@override
public void onserviceconnected(componentname name, ibinder service) {
localservice.simplebinder sbinder = (localservice.simplebinder)service;
log.v(tag, "3 + 5 = " + sbinder.add(3, 5));
log.v(tag, sbinder.getservice().tostring());
}
};
findviewbyid(r.id.btnbind).setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
bindservice(new intent(main.this, localservice.class), sc, context.bind_auto_create);
isbind = true;
}
});
findviewbyid(r.id.btnunbind).setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
if(isbind){
unbindservice(sc);
isbind = false;
}
}
});
}
}

在 activity 中,我们通过 serviceconnection 接口来取得建立连接 与 连接意外丢失的回调。bindservice有三个参数,第一个是用于区分 service 的intent 与 startservice 中的 intent 一致,第二个是实现了 serviceconnection 接口的对象,最后一个是 flag 标志位。有两个flag,bind_debug_unbind 与 bind_auto_create,前者用于调试(详细内容可以查看javadoc 上面描述的很清楚),后者默认使用。unbindservice 解除绑定,参数则为之前创建的 serviceconnection 接口对象。另外,多次调用 unbindservice 来释放相同的连接会抛出异常,因此我创建了一个 boolean 变量来判断是否 unbindservice 已经被调用过。
运行结果
Android中的Service相关全面总结
2). remote 服务绑定:remote 的服务绑定由于服务是在另外一个进程,因此需要用到 android 的 ipc 机制。这将又是一个很长的话题,因此,我打算写另外一篇 android 的 ipc 机制分析 ,并在其中进行详述,然后在这里更新链接,敬请关注。
特别注意:
1、service.onbind如果返回null,则调用 bindservice 会启动 service,但不会连接上 service,因此 serviceconnection.onserviceconnected 不会被调用,但你任然需要使用 unbindservice 函数断开它,这样 service 才会停止。
6、创建前台服务
前台服务的优点上面已经说明,但设置服务为前台服务,我们需要注意在 sdk 2.0 及其以后版本使用的方法是 startforeground 与 stopforeground,之前版本使用的是 setforeground ,因此如果你应用程序的最低运行环境要求是 2.0,那么这里可以直接运用新方法,如果运行环境是2.0以下,那么为了保证向后兼容性,这里必须使用反射技术来调用新方法。
下面是我仿照 apidemos 重新敲的代码,对某些地方进行了修改,因此更具有说明性:
复制代码 代码如下:

package com.newcj.test;
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import android.app.notification;
import android.app.notificationmanager;
import android.app.pendingintent;
import android.app.service;
import android.content.context;
import android.content.intent;
import android.os.ibinder;
public class foregroundservice extends service {
private static final class[] mstartforegroundsignature = new class[] {
int.class, notification.class};
private static final class[] mstopforegroundsignature = new class[] {
boolean.class};
private notificationmanager mnm;
private method mstartforeground;
private method mstopforeground;
private object[] mstartforegroundargs = new object[2];
private object[] mstopforegroundargs = new object[1];
@override
public ibinder onbind(intent intent) {
return null;
}
@override
public void oncreate() {
super.oncreate();
mnm = (notificationmanager)getsystemservice(context.notification_service);
try {
mstartforeground = foregroundservice.class.getmethod("startforeground", mstartforegroundsignature);
mstopforeground = foregroundservice.class.getmethod("stopforeground", mstopforegroundsignature);
} catch (nosuchmethodexception e) {
mstartforeground = mstopforeground = null;
}
// 我们并不需要为 notification.flags 设置 flag_ongoing_event,因为
// 前台服务的 notification.flags 总是默认包含了那个标志位
notification notification = new notification(r.drawable.icon, "foreground service started.",
system.currenttimemillis());
pendingintent contentintent = pendingintent.getactivity(this, 0,
new intent(this, main.class), 0);
notification.setlatesteventinfo(this, "foreground service",
"foreground service started.", contentintent);
// 注意使用 startforeground ,id 为 0 将不会显示 notification
startforegroundcompat(1, notification);
}
@override
public void ondestroy() {
super.ondestroy();
stopforegroundcompat(1);
}
// 以兼容性方式开始前台服务
private void startforegroundcompat(int id, notification n){
if(mstartforeground != null){
mstartforegroundargs[0] = id;
mstartforegroundargs[1] = n;
try {
mstartforeground.invoke(this, mstartforegroundargs);
} catch (illegalargumentexception e) {
e.printstacktrace();
} catch (illegalaccessexception e) {
e.printstacktrace();
} catch (invocationtargetexception e) {
e.printstacktrace();
}
return;
}
setforeground(true);
mnm.notify(id, n);
}
// 以兼容性方式停止前台服务
private void stopforegroundcompat(int id){
if(mstopforeground != null){
mstopforegroundargs[0] = boolean.true;
try {
mstopforeground.invoke(this, mstopforegroundargs);
} catch (illegalargumentexception e) {
e.printstacktrace();
} catch (illegalaccessexception e) {
e.printstacktrace();
} catch (invocationtargetexception e) {
e.printstacktrace();
}
return;
}
// 在 setforeground 之前调用 cancel,因为我们有可能在取消前台服务之后
// 的那一瞬间被kill掉。这个时候 notification 便永远不会从通知一栏移除
mnm.cancel(id);
setforeground(false);
}
}

特别注意: 1、使用 startforeground ,如果 id 为 0 ,那么 notification 将不会显示。
7、在什么情况下使用 startservice 或 bindservice 或 同时使用startservice 和 bindservice
如果你只是想要启动一个后台服务长期进行某项任务那么使用 startservice 便可以了。如果你想要与正在运行的 service 取得联系,那么有两种方法,一种是使用 broadcast ,另外是使用 bindservice ,前者的缺点是如果交流较为频繁,容易造成性能上的问题,并且 broadcastreceiver 本身执行代码的时间是很短的(也许执行到一半,后面的代码便不会执行),而后者则没有这些问题,因此我们肯定选择使用 bindservice(这个时候你便同时在使用 startservice 和 bindservice 了,这在 activity 中更新 service 的某些运行状态是相当有用的)。另外如果你的服务只是公开一个远程接口,供连接上的客服端(android 的 service 是c/s架构)远程调用执行方法。这个时候你可以不让服务一开始就运行,而只用 bindservice ,这样在第一次 bindservice 的时候才会创建服务的实例运行它,这会节约很多系统资源,特别是如果你的服务是remote service,那么该效果会越明显(当然在 service 创建的时候会花去一定时间,你应当注意到这点)。
8、在 androidmanifest.xml 里 service 元素的常见选项
android:name  -------------  服务类名
android:label  --------------  服务的名字,如果此项不设置,那么默认显示的服务名则为类名
android:icon  --------------  服务的图标
android:permission  -------  申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务
android:process  ----------  表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字
android:enabled  ----------  如果此项设置为 true,那么 service 将会默认被系统启动,不设置默认此项为 false
android:exported  ---------  表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false