Android Service启动源码
一、简介
Android Service的启动流程源码分析,在Android中服务有两种状态,一种是启动服务,一种是绑定服务,它们有着不同的生命周期。启动服务的生命周期:onCreate,onStart,onDestroy;绑定服务的生命周期:onCreate,onBind,onUnBind,onDestroy。至于服务具体如何使用,本篇将不做介绍。主要介绍从源码角度,解析启动服务过程。需要注意的是,阅读本篇文章之前建议先了解Activity的启动流程。
二、源码解析
通常需要在Activity组件中启动一个服务,用于在后台执行一些计算的操作。这时,会调用startService(Intent service)方法,其实这个方法的具体实现在Activity的父类ContextWrapper类中,类ContextWrapper是Context的子类。好了,查看源码开始分析吧~
查看ContextWrapper$startService源码:
@Override
public ComponentName startService(Intent service) {
return mBase.startService(service);
}
第3行,字段mBase是Context类型,但Context是一个抽象类,事实上mBase变量是一个ContextImpl对象。给mBase变量设置值是在Activity$attach方法被调用时完成,具体分析见文章Android Activity的启动流程源码解析,这里不再重复阐述。
查看ContextImpl$startService方法源码:
@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service, false, mUser);
}
//继续查看
private ComponentName startServiceCommon(Intent service, boolean requireForeground,
UserHandle user) {
//...code
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), requireForeground,
getOpPackageName(), user.getIdentifier());
//...code
}
第13行,ActivityManager.getService()返回的是一个IActivityManager的一个代理对象,利用AIDL技术完成进程间通信,需要找到那个extendsIActivityManager.Stub的实现类,它就是ActivityManagerService。IActivityManager的代理对象调用startService方法,会向系统服务ActivityManagerService发送一个请求,基于Binder机制,会调用ActivityManagerService$startService方法。详细的代码流程分析见文章Android Activity的启动流程源码解析,这里不再重复阐述。
查看ActivityManagerService$startService方法源码:
@Override
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, boolean requireForeground, String callingPackage, int userId)
throws TransactionTooLargeException {
//...code
synchronized(this) {
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
ComponentName res;
try {
res = mServices.startServiceLocked(caller, service,
resolvedType, callingPid, callingUid,
requireForeground, callingPackage, userId);
} finally {
Binder.restoreCallingIdentity(origId);
}
return res;
}
}
第14行,变量mServices是ActiveServices类型的对象。于是,启动服务的工作交给了ActiveServices来处理。
查看ActiveServices源码如下:
ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
throws TransactionTooLargeException {
//...code
ServiceLookupResult res =
retrieveServiceLocked(service, resolvedType, callingPackage,