原文来自于 Gityuan startService启动过程分析Service 流程分析 源码更新于 AndroidCodeSearch (现在是 Android 11) ,老版本代码查看于 opersys

一、概述

经历了之前的 无 Binder 不 Android ,相信对 Binder 架构有了较深地理解。Binder 的地位是非常之重要,整个 Java framework 的提供ActivityManagerServicePackageManagerService 等服务都是基于 Binder 架构来通信的,另外 Handle 消息机制 在进程内的通信使用非常多。本文将开启对 ActivityManagerService 的分析。

ActivityManagerServiceAndroidJava framework 的服务框架最重要的服务之一。

对于 AndoridActivityServiceBroadcastContentProvider 四剑客的管理,包含其生命周期都是通过 ActivityManagerService 来完成的。

1.1 ActivityManagerService 介绍

缩写

  • AMP:ActivityManagerProxy
  • AMN:ActivityManagerNative
  • AMS:ActivityManagerService
  • AT:ApplicationThread
  • ATP:ApplicationThreadProxy
  • ATN:ApplicationThreadNative
  • IAM:IActivityManager
  • IAT:IApplicationThread
  • ACF:AppComponentFactory
  • CW:ContextWrapper
  • CI:ContextImpl
  • LA:LoadeAPK

Android 7.0

Android7 之前(包括7.07.1),AMS 是通过自己实现代理类来完成 Binder

AMS 通信是基于其代理 AMP(通过 ActivityManagerNative. getDefault 得到其内部类 ActivityManagerProxy 的单例对象,即 AMS 在客户端(用户进程)的代理对象)

图片来源于《Gityuan》

Activity 的直接管理者是 ActivityManager,但最终管理者是 AMS

  • Client 端发起启动 Service 请求;
  • AM 会通过 ActivityManagerNativegetDefault 来得到其内部类 ActivityManagerProxy 的单例对象,即 AMS 在客户端(用户进程)的代理对象;
  • 作为代理类,AMP 中含有 AMS 的引用,AMNAMP 都实现了 IActivityManager
  • IActivityManager 继承了 IInterface(实现 Binder 通信的必备条件),所以 AMP 具备了 Binder 通信能力;
  • startService 最终会通过 AMP 中的 AMS 引用来调用 AMStransact 方法;
  • AMS 发送启动 Service 请求,并将序列化数据传递给 AMS ,随后 AMS 的子类 AMNonTransact 会执行,它会将具体的启动工作交给 ActivityStater 来负责;

Android 8.0

8.0 开始,AMS 通过 AIDL 完成 Binder 通信

AMS 中主要涉及这三个数据结构:ActivityRecordTaskRecordActivityStack

  • ActivityRecord:存储 Activity 的相关信息,比如 AndroidMainifes 的节点信息,启动 Activity 的包名,所在进程,图标主题标识符,当前 Activity 状态,所属 TaskRecord 等;
  • TaskRecord:描述一个 Activity 任务栈,主要维护了一个按历史顺序排列的 ArrayList<ActivityRecord>,并包含此任务栈所属的 ActivityStack 等;
  • ActivityStack:一个管理系统中所有 Activity 的管理类,真实交由 ActivityStackSupervisor 管理,内部维护了 Activity 的所有状态,并对不同状态的 Activity 进行分类管理,如最近启动的 Activity,正在暂停的 Activity 等。

IActivityManager.java 就是 ADIL 文件所对应的 java 文件,里面包含了 ProxyStub

图片来源于网络

1.2 ApplicationThread

Android 7.0

Android 7 之前(包括7.07.1),AT 是通过自己实现代理类来完成 Binder

图片来源于网络

IActivityManagerbinder 通信原理一样,ApplicationThreadProxy 作为 binder 通信的客户端,ApplicationThreadNative 作为 Binder 通信的服务端,其中ApplicationThread 继承 ApplicationThreadNative 类,覆写其中的部分方法。

Android 8.0

8.0 开始,AT 通过 AIDL 完成 Binder 通信

  • IApplivation.Thread.Stub 代替 ApplicationThreadNative
  • IApplivation.Thread.Stub.Proxy 代替 ApplicationThreadProxy

1.3 启动服务流程图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
frameworks/base/services/core/java/com/android/server/am/
- ActivityManagerService.java
- ActiveServices.java
- ServiceRecord.java
- ProcessRecord.java

out/soong/.intermediates/frameworks/base/framework-minus-apex/android_common/xref30/srcjars.xref/android/app/
- IActivityManager.java (AIDL 文件生成的,内含 Proxy 和 Stub)
- IApplicationThread.java (AIDL 文件生成的,内含 Proxy 和 Stub)

frameworks/base/core/java/android/app/
- ActivityManager.java

- IApplicationThread.java
- ActivityThread.java (内含 ApplicationThread )

- ContextImpl.java

- LoadedApk.java

frameworks/base/core/java/android/content/
- ContextWrapper.java

图片来源于网络

接下来,我们正式从代码角度来分析服务启动的过程。

二、startService 源码

2.1 CW.startService

1
2
3
4
5
6
ContextWrapper.java

@Override
public ComponentName startService(Intent service) {
return mBase.startService(service); // 其中 mBase 为 ContextImpl 对象 【 见流程2.2 】
}

2.2 CI.startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ContextImpl.java

@Override
public ComponentName startService(Intent service) {
// 当 system 进程调用此方法时输出 warn 信息,system 进程建立调用 startServiceAsUser 方法
warnIfCallingFromSystemProcess();
return startServiceCommon(service, false, mUser);
}

private ComponentName startServiceCommon(Intent service, boolean requireForeground,
UserHandle user) {
try {
// 检验 service,当 service 为空则 throw 异常
validateServiceIntent(service);
service.prepareToLeaveProcess(this);
// ActivityManager.getService() 就是获取到的 Proxy 对象 【见 2.3】 【startService 见 2.3.1】
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), requireForeground,
getOpPackageName(), user.getIdentifier());
//...
return cn;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}

2.3 AM.getService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
ActivityManager.java

public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}

Singleton.java

@UnsupportedAppUsage
public final T get() {
synchronized (this) {
if (mInstance == null) {
//首次调用 create() 来获取AMP对象
mInstance = create();
}
return mInstance;
}
}

ActivityManager.java

private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
//获取名为 "activity" 的服务,服务都注册到 ServiceManager 来统一管理
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
// IActivityManager 是 aidl,也就说明 Service 的启动过程是一个IPC的过程
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};

IActivityManager.java

public static android.app.IActivityManager asInterface(android.os.IBinder obj){
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof android.app.IActivityManager))) {
return ((android.app.IActivityManager)iin);
}
// 返回 Proxy 类
return new android.app.IActivityManager.Stub.Proxy(obj);
}

create 方法返回的是 AIDL 生成的代理类,IActivityManager.Stub.Proxy, 那么下一步调用 IActivityManager.Stub.Proxy.startService 方法。

通过 Binder 通信过程中,

  • 提供了一个 IActivityManager 服务接口(继承于 android.os.IInterface)
  • IActivityManager.Stub.Proxy 类实现了 IActivityManager 接口
  • IActivityManager.Stub 继承 Binder 并且实现 IActivityManager 接口
  • ActivityManagerService 继承自 IActivityManager.Stub

这里可以看出 IActivityManager.Stub.ProxyBinder 通信的客户端,ActivityManagerServiceBinder 通信的服务端,那么IActivityManager.Proxy.startService() 最终调用的是 ActivityManagerService.startService()

2.3.1 IAM.Stub.Proxy.startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 由于是 编译器生成的代码,排版可能比较乱    IActivityManager.java  

@Override public android.content.ComponentName startService(android.app.IApplicationThread caller, android.content.Intent service, java.lang.String resolvedType, boolean requireForeground, java.lang.String callingPackage, java.lang.String callingFeatureId, int userId) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
android.content.ComponentName _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((caller!=null))?(caller.asBinder()):(null)));
if ((service!=null)) {
_data.writeInt(1);
service.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
_data.writeString(resolvedType);
_data.writeInt(((requireForeground)?(1):(0)));
_data.writeString(callingPackage);
_data.writeString(callingFeatureId);
_data.writeInt(userId);
//通过 Binder 传递数据 【见 2.3.2】
boolean _status = mRemote.transact(Stub.TRANSACTION_startService, _data, _reply, 0);
if (!_status) {
if (getDefaultImpl() != null) {
return getDefaultImpl().startService(caller, service, resolvedType, requireForeground, callingPackage, callingFeatureId, userId);
}
}
_reply.readException();
if ((0!=_reply.readInt())) {
_result = android.content.ComponentName.CREATOR.createFromParcel(_reply);
}
else {
_result = null;
}
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}

2.3.2 IAM.Stub.onTransact(Client -> Service)

到这里,借助 IAM 这个 AIDL ,便完成了从 Service 所在的进程(Client 的进程)到了 system_server 进程(服务进程)的调用过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 由于是 编译器生成的代码,排版可能比较乱    IActivityManager.java  

@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
...
case TRANSACTION_startService:
{
data.enforceInterface(descriptor);
//生成 IApplicationThread 的代理对象,即 IApplicationThread.Stub.Proxy 对象
android.app.IApplicationThread _arg0;
_arg0 = android.app.IApplicationThread.Stub.asInterface(data.readStrongBinder());
android.content.Intent _arg1;
if ((0!=data.readInt())) {
_arg1 = android.content.Intent.CREATOR.createFromParcel(data);
}
else {
_arg1 = null;
}
java.lang.String _arg2;
_arg2 = data.readString();
boolean _arg3;
_arg3 = (0!=data.readInt());
java.lang.String _arg4;
_arg4 = data.readString();
java.lang.String _arg5;
_arg5 = data.readString();
int _arg6;
_arg6 = data.readInt();
//调用 ActivityManagerService 的 startService() 方法 【见 2.4】
android.content.ComponentName _result = this.startService(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5, _arg6);
reply.writeNoException();
if ((_result!=null)) {
reply.writeInt(1);
_result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
}
else {
reply.writeInt(0);
}
return true;
}
}

在整个调用过程涉及两个进程,令 startService 的发起进程记为进程 AServiceManagerService 记为进程 B ;那么进程 A 通过 Binder 机制(采用 IActivityManager 接口)向进程B发起请求服务,进程 B 则通过 Binder 机制(采用 IApplicationThread 接口)向进程 A 发起请求服务。也就是说进程 A 与进程 B 能相互间主动发起请求,进程通信。

2.4 AMS.startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Override
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, boolean requireForeground, String callingPackage, int userId)
throws TransactionTooLargeException {
// 当调用者是孤立进程,则抛出异常。
enforceNotIsolatedCaller("startService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}

if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}

if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
"*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
synchronized(this) {
final int callingPid = Binder.getCallingPid();// 调用者 pid
final int callingUid = Binder.getCallingUid();// 调用者 uid
final long origId = Binder.clearCallingIdentity();
ComponentName res;
try {
// 调用 ActiveServices 的 startServiceLocked() 方法 【见 2.5】
res = mServices.startServiceLocked(caller, service,
resolvedType, callingPid, callingUid,
requireForeground, callingPackage, userId);
} finally {
Binder.restoreCallingIdentity(origId);
}
return res;
}
}

参数说明

  • caller: IApplicationThread 类型,复杂处理
  • service: Intent 类型,包含需要运行的 service 信息
  • *resolvedType: * String 类型
  • callingPackage: String 类型,调用该方法的 package
  • userId: int 类型,用户的 id

2.5 AS.startServiceLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
throws TransactionTooLargeException {
final boolean callerFg;
if (caller != null) {
final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
if (callerApp == null) {
throw new SecurityException("");//抛出异常,此处省略异常字符串
}
callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
} else {
callerFg = true;
}
//检索服务信息
ServiceLookupResult res = retrieveServiceLocked(service, resolvedType, callingPackage,
callingPid, callingUid, userId, true, callerFg, false, false);
if (res == null) {
return null;
}
if (res.record == null) {
return new ComponentName("!", res.permission != null ? res.permission : "private to package");
}
// 取出 ServiceRecord 对象,后面启动过程中都是使用的它
ServiceRecord r = res.record;
// 检查是否存在启动服务的 user
if (!mAm.mUserController.exists(r.userId)) {
Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
return null;
}

// ... 省略 判断和处理前台服务

r.lastActivity = SystemClock.uptimeMillis();
r.startRequested = true;// 启动服务标识置为 true
r.delayedStop = false;
r.fgRequired = fgRequired;
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
service, neededGrants, callingUid));

// ... 省略 对于非前台进程的调度

// 调用 startServiceInnerLocked() 方法 【见 2.6】
ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
return cmp;
}

有一种重要的标记符 callerFg , 用于标记是前台还是后台:

  • 当发起方进程不等于 ProcessList.SCHED_GROUP_BACKGROUND ,或者发起方为空, 则 callerFg= true
  • 否则,callerFg= false

2.6 AS.startServiceInnerLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
ServiceState stracker = r.getTracker();
if (stracker != null) {
stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
}
r.callStart = false;
synchronized (r.stats.getBatteryStats()) {
r.stats.startRunningLocked(); //用于耗电统计,开启运行的状态
}
// bringUpServiceLocked 【见 2.7】
String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
if (error != null) {
return new ComponentName("!!", error);
}

if (r.startRequested && addToStarting) {
boolean first = smap.mStartingBackground.size() == 0;
smap.mStartingBackground.add(r);
r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
if (DEBUG_DELAYED_SERVICE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
} else if (DEBUG_DELAYED_STARTS) {
Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
}
if (first) {
smap.rescheduleDelayedStartsLocked();
}
} else if (callerFg || r.fgRequired) {
smap.ensureNotStartingBackgroundLocked(r);
}

return r.name;
}

2.7 AS.bringUpServiceLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
// 已经启动,重复启动时,直接发送参数调动 onStartCommand() 方法
if (r.app != null && r.app.thread != null) {
// 调用 service.onStartCommand() 过程
sendServiceArgsLocked(r, execInFg, false);
return null;
}

if (!whileRestarting && mRestartingServices.contains(r)) {
//等待延迟重启的过程,则直接返回
return null;
}

// 启动 service 前,把 service 从重启服务队列中移除
if (mRestartingServices.remove(r)) {
clearRestartingIfNeededLocked(r);
}

// service 正在启动,将 delayed 设置为 false
if (r.delayed) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
r.delayed = false;
}

// 确保拥有该服务的 user 已经启动,否则停止;
if (!mAm.mUserController.hasStartedUserState(r.userId)) {
String msg = "Unable to launch app "
+ r.appInfo.packageName + "/"
+ r.appInfo.uid + " for service "
+ r.intent.getIntent() + ": user " + r.userId + " is stopped";
Slog.w(TAG, msg);
bringDownServiceLocked(r);
return msg;
}

try {
// 服务正在启动,设置 package 停止状态为 false
AppGlobals.getPackageManager().setPackageStoppedState(
r.packageName, false, r.userId);
} catch (RemoteException e) {
} catch (IllegalArgumentException e) {
Slog.w(TAG, "Failed trying to unstop package " + r.packageName + ": " + e);
}

final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
final String procName = r.processName;
String hostingType = "service";
ProcessRecord app;

if (!isolated) {
// 根据进程名和 uid,查询 ProcessRecord
app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
if (app != null && app.thread != null) {
try {
app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
// 调用 realStartServiceLocked() 方法 启动服务 【见 2.8】
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
}
} else {
app = r.isolatedProc;
if (WebViewZygote.isMultiprocessEnabled()
&& r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
hostingType = "webview_service";
}
}
// 对于进程没有启动的情况
if (app == null && !permissionsReviewRequired) {
// 启动 service 所要运行的进程 【见 2.7.1】
if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
hostingType, r.name, false, isolated, false)) == null) {
bringDownServiceLocked(r);// 进程启动失败
return msg;
}
if (isolated) {
r.isolatedProc = app;
}
}

if (r.fgRequired) {
mAm.tempWhitelistUidLocked(r.appInfo.uid,SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
}

if (!mPendingServices.contains(r)) {
mPendingServices.add(r);
}

if (r.delayedStop) {
r.delayedStop = false;
if (r.startRequested) {
stopServiceLocked(r); //停止服务
}
}

return null;
}
  • 当目标进程已存在,则直接执行 realStartServiceLocked()
  • 当目标进程不存在,则先执行 startProcessLocked(过程待更新 Android四大组件与进程启动的关系) 创建进程, 经过层层调用最后会调用到 AMS.attachApplicationLocked, 然后再执行 realStartServiceLocked()

对于非前台进程调用而需要启动的服务,如果已经有其他的后台服务正在启动中,那么我们可能希望延迟其启动。这是用来避免启动同时启动过多的进程(非必须的)。

2.7.1 AMS.attachApplicationLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
...
thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked());

...
if (!badApp) {
try {
//寻找所有需要在该进程中运行的服务 【见 2.7.2】
didSomething |= mServices.attachApplicationLocked(app, processName);
} catch (Exception e) {
badApp = true;
}
}
...
return true;
}

2.7.2 AS.attachApplicationLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
boolean attachApplicationLocked(ProcessRecord proc, String processName)
throws RemoteException {
boolean didSomething = false;
//启动 mPendingServices 队列中,等待在该进程启动的服务
if (mPendingServices.size() > 0) {
ServiceRecord sr = null;
try {
for (int i=0; i<mPendingServices.size(); i++) {
sr = mPendingServices.get(i);
if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
|| !processName.equals(sr.processName))) {
continue;
}

mPendingServices.remove(i);
i--;
// 将当前服务的包信息加入到 proc
proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,mAm.mProcessStats);
// 启动服务,即将进入服务的生命周期
realStartServiceLocked(sr, proc, sr.createdFromFg);
didSomething = true;
if (!isServiceNeededLocked(sr, false, false)) {
bringDownServiceLocked(sr);
}
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting service " + sr.shortName, e);
throw e;
}
}
// 对于正在等待重启并需要运行在该进程的服务,现在是启动它们的大好时机
if (mRestartingServices.size() > 0) {
ServiceRecord sr;
for (int i=0; i<mRestartingServices.size(); i++) {
sr = mRestartingServices.get(i);
if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
|| !processName.equals(sr.processName))) {
continue;
}
mAm.mHandler.removeCallbacks(sr.restarter);
mAm.mHandler.post(sr.restarter);
}
}
return didSomething;
}
  • 当需要创建新进程,则创建后经历过 attachApplicationLocked,则会再调用 realStartServiceLocked()
  • 当不需要创建进程,即在上一步中直接就进入了 realStartServiceLocked()

2.8 AS.realStartServiceLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
if (app.thread == null) {
throw new RemoteException();
}

r.app = app;
r.restartTime = r.lastActivity = SystemClock.uptimeMillis();

final boolean newService = app.services.add(r);
// 发送 delay 消息 【见 2.8.1】
bumpServiceExecutingLocked(r, execInFg, "create");
mAm.updateLruProcessLocked(app, false, null);
updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
mAm.updateOomAdjLocked();

boolean created = false;
try {
if (LOG_SERVICE_START_STOP) {
String nameTerm;
int lastPeriod = r.shortName.lastIndexOf('.');
nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
EventLogTags.writeAmCreateService(
r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
}
synchronized (r.stats.getBatteryStats()) {
r.stats.startLaunchedLocked();
}
mAm.notifyPackageUse(r.serviceInfo.packageName,
PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
// 服务进入 onCreate(),调用 ActivityThread 的 scheduleCreateService() 方法 【见 2.9】
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
r.postNotification();
created = true;
} catch (DeadObjectException e) {
mAm.appDiedLocked(app); // 应用死亡处理
throw e;
} finally {
if (!created) {
// Keep the executeNesting count accurate.
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
if (newService) {
app.services.remove(r);
r.app = null;
}

// 尝试重新启动服务
if (!inDestroying) {
scheduleServiceRestartLocked(r, false);
}
}
}

if (r.whitelistManager) {
app.whitelistManager = true;
}
requestServiceBindingsLocked(r, execInFg);
updateServiceClientActivitiesLocked(app, null, true);

// 如果是启动,并且需要调用 onStartCommand() 方法,给 pendingStarts 集合增加数据,
// 因为 onStartCommand() 方法是否会调动是根据 pendingStarts 集合是否有数据来决定是否调用的。
// 在后面说参数调用的时候就会知道,如果仅仅是绑定服务,就不会添加,这也就是为什么我们绑定服务时不会回调 onStartCommand() 方法的原因
if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),null, null, 0));
}
// 服务 进入 onStartCommand() 【见 2.15】
sendServiceArgsLocked(r, execInFg, true);

if (r.delayed) {
getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
r.delayed = false;
}

if (r.delayedStop) {
r.delayedStop = false;
if (r.startRequested) {
stopServiceLocked(r); //停止服务
}
}
}

2.8.1 AS.bumpServiceExecutingLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
boolean timeoutNeeded = true;
if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
&& (r.app != null) && (r.app.pid == android.os.Process.myPid())) {
timeoutNeeded = false;
}
// ...
if (r.executeNesting == 0) {
// ...
} else if (r.app != null && fg && !r.app.execServicesFg) {
r.app.execServicesFg = true;
if (timeoutNeeded) {
scheduleServiceTimeoutLocked(r.app); // 【见 2.8.2】
}
}
// ...
}

2.8.2 AS.scheduleServiceTimeoutLocked

1
2
3
4
5
6
7
8
9
10
11
void scheduleServiceTimeoutLocked(ProcessRecord proc) {
if (proc.executingServices.size() == 0 || proc.thread == null) {
return;
}
Message msg = mAm.mHandler.obtainMessage(
ActivityManagerService.SERVICE_TIMEOUT_MSG);
msg.obj = proc;
// 当超时后仍没有 remove 该 SERVICE_TIMEOUT_MSG 消息,则执行 service Timeout 流程
mAm.mHandler.sendMessageDelayed(msg,
proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
}

发送延时消息 `SERVICE_TIMEOUT_MSG 延时时长:

  • 对于前台服务,则超时为 SERVICE_TIMEOUT,即 timeout=20s
  • 对于后台服务,则超时为 SERVICE_BACKGROUND_TIMEOUT,即 timeout=200s

2.9 IAT.Stub.Proxy.scheduleCreateService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Override public void scheduleCreateService(android.os.IBinder token, android.content.pm.ServiceInfo info, android.content.res.CompatibilityInfo compatInfo, int processState) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder(token);
if ((info!=null)) {
_data.writeInt(1);
info.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
if ((compatInfo!=null)) {
_data.writeInt(1);
compatInfo.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
_data.writeInt(processState);
//【见 2.9.1】
boolean _status = mRemote.transact(Stub.TRANSACTION_scheduleCreateService, _data, null, android.os.IBinder.FLAG_ONEWAY);
if (!_status) {
if (getDefaultImpl() != null) {
getDefaultImpl().scheduleCreateService(token, info, compatInfo, processState);
return;
}
}
}
finally {
_data.recycle();
}
}

2.9.1 IAT.Stub.onTransact (Service -> Client)

到这里,借助 IAT 这个 AIDL ,便完成了从 system_server 进程(服务进程)到了 Service 所在的进程(Client 的进程)的调用过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
...
case TRANSACTION_scheduleCreateService:
{
data.enforceInterface(descriptor);
android.os.IBinder _arg0;
_arg0 = data.readStrongBinder();
android.content.pm.ServiceInfo _arg1;
if ((0!=data.readInt())) {
_arg1 = android.content.pm.ServiceInfo.CREATOR.createFromParcel(data);
}
else {
_arg1 = null;
}
android.content.res.CompatibilityInfo _arg2;
if ((0!=data.readInt())) {
_arg2 = android.content.res.CompatibilityInfo.CREATOR.createFromParcel(data);
}
else {
_arg2 = null;
}
int _arg3;
_arg3 = data.readInt();
//调用 ActivityThread.ApplicationThread 的 scheduleCreateService() 方法 【见 2.9.2】
this.scheduleCreateService(_arg0, _arg1, _arg2, _arg3);
return true;
}
}

2.9.2 AT.scheduleCreateService

1
2
3
4
5
6
7
8
9
10
11
12
public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();// 准备服务创建所需的数据
s.token = token;
s.info = info;
s.compatInfo = compatInfo;
// 给 Handler 类 H 发送 CREATE_SERVICE 【见 2.10】
sendMessage(H.CREATE_SERVICE, s);
}

final H mH = new H();

HActivityThread 的内部类,继承 Handler

2.10 AT.H.handleMessage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}

mH.sendMessage(msg);
}

class H extends Handler {
// ...
public void handleMessage(Message msg) {
switch (msg.what) {
case CREATE_SERVICE:
handleCreateService((CreateServiceData)msg.obj);
break;
case BIND_SERVICE:
handleBindService((BindServiceData)msg.obj);
break;
case UNBIND_SERVICE:
handleUnbindService((BindServiceData)msg.obj);
break;
case SERVICE_ARGS:
handleServiceArgs((ServiceArgsData)msg.obj);
break;
case STOP_SERVICE:
handleStopService((IBinder)msg.obj);
break;
}
//...
}
}

2.11 AT.handleCreateService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private void handleCreateService(CreateServiceData data) {
// 当应用处于后台即将进行 GC,而此时被调回到活动状态,则跳过本次 gc。
unscheduleGcIdler();
LoadedApk packageInfo = getPackageInfoNoCheck(data.info.applicationInfo, data.compatInfo);
// 通过反射创建目标服务对象
Service service = null;
try {
// 使用类加载器通过反射的形势创建 Service 对象
java.lang.ClassLoader cl = packageInfo.getClassLoader();
// packageInfo.getAppFactory()【见 2.11.1】
// instantiateService 【见 2.12】
service = packageInfo.getAppFactory().instantiateService(cl, data.info.name, data.intent);
} catch (Exception e) {
//...
}

try {
// 创建 ContextImpl 对象
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);
// 创建 Application 对象
Application app = packageInfo.makeApplication(false, mInstrumentation);
// Serivce 的 attach() 回调,并建立 Service 和 ContextImpl 之间的联系 【见 2.13】
service.attach(context, this, data.info.name, data.token, app,ActivityManager.getService());
// 调用服务 onCreate() 方法 【见 2.13】
service.onCreate();
// 将Service保存到集合中 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
mServices.put(data.token, service);
try {
// 调用服务创建完成 【见 2.14】
ActivityManager.getService().serviceDoneExecuting(data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
//...
}
} catch (Exception e) {
//...
}
}

2.11.1 packageInfo.getAppFactory()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public AppComponentFactory getAppFactory() {
return mAppComponentFactory;
}

// 给 mAppComponentFactory 赋值
private AppComponentFactory createAppFactory(ApplicationInfo appInfo, ClassLoader cl) {
if (appInfo.appComponentFactory != null && cl != null) {
try {
return (AppComponentFactory) cl.loadClass(appInfo.appComponentFactory)
.newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
Slog.e(TAG, "Unable to instantiate appComponentFactory", e);
}
}
return AppComponentFactory.DEFAULT;
}

2.12 ACF.instantiateService

1
2
3
4
5
6
public @NonNull Service instantiateService(@NonNull ClassLoader cl,
@NonNull String className, @Nullable Intent intent)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// 通过反射创建 Service
return (Service) cl.loadClass(className).newInstance();
}

2.13 Service.attach/onCreate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {

public final void attach(
Context context,
ActivityThread thread, String className, IBinder token,
Application application, Object activityManager) {
attachBaseContext(context);
mThread = thread;
mClassName = className;
mToken = token;
mApplication = application;
mActivityManager = (IActivityManager)activityManager;
mStartCompatibility = getApplicationInfo().targetSdkVersion
< Build.VERSION_CODES.ECLAIR;
}

public void onCreate(){ }
}

最终调用 Service.onCreate() 方法,对于目标服务都是继承于 Service ,并覆写该方式,调用目标服务的 onCreate() 方法。拨云见日,到此总算是进入了 Service 的生命周期。

2.14 AMS.serviceDoneExecuting

1
2
3
4
5
6
public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
synchronized(this) {
//...
mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
}
}

2.8.1bumpServiceExecutingLocked 发送一个延时消息 SERVICE_TIMEOUT_MSG

2.14.1 AS.serviceDoneExecutingLocked

1
2
3
4
5
6
7
8
9
10
11
12
void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
boolean inDestroying = mDestroyingServices.contains(r);
if (r != null) {
//...
final long origId = Binder.clearCallingIdentity();
// 【见 2.14.2】
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
Binder.restoreCallingIdentity(origId);
} else {
//...
}
}

2.14.2 AS.serviceDoneExecutingLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,boolean finishing) {
r.executeNesting--;
if (r.executeNesting <= 0) {
if (r.app != null) {
r.app.execServicesFg = false;
r.app.executingServices.remove(r);
if (r.app.executingServices.size() == 0) {
// 移除服务启动超时的消息
mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
} else if (r.executeFg) {
// ...
}
if (inDestroying) {
mDestroyingServices.remove(r);
r.bindings.clear();
}
mAm.updateOomAdjLocked(r.app, true);
}
r.executeFg = false;
// ...
if (finishing) {
if (r.app != null && !r.app.persistent) {
r.app.services.remove(r);
if (r.whitelistManager) {
updateWhitelistManagerLocked(r.app);
}
}
r.app = null;
}
}
}

handleCreateService() 执行后便会移除服务启动超时的消息 SERVICE_TIMEOUT_MSGService 启动过程出现 ANR”executing service [发送超时serviceRecord信息]”, 这往往是 serviceonCreate() 回调方法执行时间过长。

2.8 AS.realStartServiceLocked 方法在完成 onCreate 操作,解析来便是进入 onStartCommand 方法.

2.15 AS.sendServiceArgsLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
boolean oomAdjusted) throws TransactionTooLargeException {
final int N = r.pendingStarts.size();
if (N == 0) {
return;
}
ArrayList<ServiceStartArgs> args = new ArrayList<>();
while (r.pendingStarts.size() > 0) {
ServiceRecord.StartItem si = r.pendingStarts.remove(0);
if (si.intent == null && N > 1) {
continue;
}
si.deliveredTime = SystemClock.uptimeMillis();
r.deliveredStarts.add(si);
si.deliveryCount++;
if (si.neededGrants != null) {
mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
si.getUriPermissionsLocked());
}
mAm.grantEphemeralAccessLocked(r.userId, si.intent,
r.appInfo.uid, UserHandle.getAppId(si.callingId));
// 标记启动开始 【见 2.8.1】
bumpServiceExecutingLocked(r, execInFg, "start");
if (!oomAdjusted) {
oomAdjusted = true;
mAm.updateOomAdjLocked(r.app, true);
}
if (r.fgRequired && !r.fgWaiting) {
//...
}
int flags = 0;
if (si.deliveryCount > 1) {
flags |= Service.START_FLAG_RETRY;
}
if (si.doneExecutingCount > 0) {
flags |= Service.START_FLAG_REDELIVERY;
}
args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
}

ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
slice.setInlineCountLimit(4);
Exception caughtException = null;
try {
//该过程类似 [流程 2.9 ~ 2.10],只是服务端调用不同客户端的方法,最终会调用 AT.handleServiceArgs -> onStartCommand
r.app.thread.scheduleServiceArgs(r, slice);
} catch (Exception e) {
caughtException = e;
}

if (caughtException != null) {
final boolean inDestroying = mDestroyingServices.contains(r);
for (int i = 0; i < args.size(); i++) {
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
}
if (caughtException instanceof TransactionTooLargeException) {
throw (TransactionTooLargeException)caughtException;
}
}
}

三、bindService 源码

图片来源于网络

3.1 CW.bindService

1
2
3
4
5
6
7
ContextWrapper.java

@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}

3.2 CI.bindService

1
2
3
4
5
6
7
8
ContextImpl.java

@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), getUser());
}

3.3 CI.bindServiceCommon

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
String instanceName, Handler handler, Executor executor, UserHandle user) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (handler != null && executor != null) {
throw new IllegalArgumentException("Handler and Executor both supplied");
}
// mPackageInfo 为 LoadedApk
if (mPackageInfo != null) {
if (executor != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
} else {
// handler 不为 null,将 ServiceConnection 封装成 IServiceConnection
// IServiceConnection 就是 LoadedApk.ServiceDispatcher.InnerConnection 类
// 将 conn 保持到InnerConnection中,handler 为主线程 Handler,也就是 ActivityThread 的内部类 H 对象
// 【见 4.1】
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
}
} else {
throw new RuntimeException("Not supported in system context");
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
&& mPackageInfo.getApplicationInfo().targetSdkVersion
< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
flags |= BIND_WAIVE_PRIORITY;
}
service.prepareToLeaveProcess(this);
// 调用 AMS 的 bindIsolatedService() 方法 【见 3.4】
int res = ActivityManager.getService().bindIsolatedService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
if (res < 0) {
throw new SecurityException("Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}

注意:在这里需要注意以上注释的地方,因为绑定 Service 最终客户端要回调 ServiceConnection 对象的 onServiceConnected() 方法,mPackageInfo.getServiceDispatcher() 就是将我们调用 bindService() 方法传递的 ServiceConnection 对象封装成 IServiceConnection(实现类为LoadedApk.ServiceDispatcher.InnerConnection) 。这是一个 aidl 接口,这是因为 Service 启动和绑定时跨进程的,普通的 ServiceConnection 是不能款进程传输的,所以需要进行封装与转换成 aidl 类型。

ActivityManager.getService().bindIsolatedService 这里不做过多讲解,上面已经讲过了,最终调用的是 AMSbindIsolatedService

3.4 AMS.bindIsolatedService

1
2
3
4
5
6
7
8
9
10
11
public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String instanceName,
String callingPackage, int userId) throws TransactionTooLargeException {
// ...

synchronized(this) {
// 调用 ActiveServices 的 bindServiceLocked() 方法 【见 3.5】
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, instanceName, callingPackage, userId);
}
}

3.5 AS.bindServiceLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, final IServiceConnection connection, int flags,
String instanceName, String callingPackage, final int userId)
throws TransactionTooLargeException {
// ... 省略
ServiceLookupResult res =
retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
callingPid, callingUid, userId, true,
callerFg, isBindExternal, allowInstant);
ServiceRecord s = res.record;
try {
// 绑定服务时,调用 ServiceRecord 的 retrieveAppBindingLocked() 方法,
// 在该方法中给 ServiceRecord的 bindings 添加绑定记录
AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
ConnectionRecord c = new ConnectionRecord(b, activity,
connection, flags, clientLabel, clientIntent,
callerApp.uid, callerApp.processName, callingPackage);

IBinder binder = connection.asBinder();
s.addConnection(binder, c);
b.connections.add(c);
if (activity != null) {
activity.addConnection(c);
}
b.client.connections.add(c);
c.startAssociationIfNeeded();
// ... 省略
if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
// 【见 3.6】
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
permissionsReviewRequired) != null) {
return 0;
}
}
// ... 省略
} finally {
Binder.restoreCallingIdentity(origId);
}

return 1;
}

注意,上面注释部分,绑定服务时,我们将连接对象保存到了 ServiceRecord 中。

3.6 AS.bringUpServiceLocked

绑定服务到这里,后面调用 attach()onCreate() 方法就和启动服务时一样的了 见 startService 2.7 ,在 bringUpServiceLocked() 中 调用
realStartServiceLocked() 方法,接着继续往下调用。

1
2
3
4
5
6
7
8
9
10
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
// ...
// 调用 realStartServiceLocked() 方法 启动服务 【见 3.7】
realStartServiceLocked(r, app, execInFg);

// ...
return null;
}

3.7 AS.realStartServiceLocked

这一步,和启动 Service 不一样的是,在 realStartServiceLocked() 方法中会调用 requestServiceBindingsLocked() 方法,处理绑定服务的过程 (其他过程请看 startService 2.8)

1
2
3
4
5
6
7
8
9
10
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
//...
// 【见 3.14】
requestServiceBindingsLocked(r, execInFg);
//...
// 服务 进入 onStartCommand() 【见 2.15】
sendServiceArgsLocked(r, execInFg, true);
//...
}

流程图中 [8 -13] 对应 startService 中的 [9 - 14]

这里省略 3.8 - 3.13

3.14 AS.requestServiceBindingsLocked

1
2
3
4
5
6
7
8
9
10
private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
throws TransactionTooLargeException {
// 根据 ServiceRecord 的 bindings 是否有数据调用 requestServiceBindingLocked() 方法,在上一步给它添加了数据 【见 3.15】
for (int i=r.bindings.size()-1; i>=0; i--) {
IntentBindRecord ibr = r.bindings.valueAt(i);
if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
break;
}
}
}

根据是否有连接对象判断是否需要调用 ActiveServices 中的requestServiceBindingLocked() 方法(和当前方法差了个 s,bindings),绑定 ServiceActiveServices 中的 bindServiceLocked() 方法中添加了,所以集合肯定不会为空

3.15 AS.requestServiceBindingLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {

if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
// 调用 ActivityThread 的 scheduleBindService() 方法 【见 3.18】
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, r.app.getReportedProcState());
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
} catch (TransactionTooLargeException e) {
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
throw e;
} catch (RemoteException e) {
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
return false;
}
}
return true;
}

[15 - 17] 就是 Service 端到 Client 端的调用,类似 startService[2.9 - 2.10]

这里省略 3.16 - 3.17

3.18 AT.handleBindService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);

if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
// 调用 Service 的 onBind() 方法 【见 3.19】
IBinder binder = s.onBind(data.intent);
// 这里调用 ActivityManagerService 的 publishService() 方法 【见 4.2】
ActivityManager.getService().publishService(
data.token, data.intent, binder);
} else {
// 如果是重新绑定,就调用 Service 的 onRebind() 方法 【见 3.19】
s.onRebind(data.intent);
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
}
}
}
}

3.19 onBind/onRebind

在上面的方法中我们已经看到了 ServiceonBind() 或者 onRebind() 方法已经被调用了,那么对于Service类来说已经执行完成了。但是我们绑定Service,客户端需要拿到 IBinder 对象,这个对象是在 ServiceConnection 对象的回调 onServiceConnected() 方法取到的,所以我们继续看看这个过程是怎样的。

四、bindService 回调

4.1 LA.getServiceDispatcher

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@UnsupportedAppUsage
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
return getServiceDispatcherCommon(c, context, handler, null, flags);
}

private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,
Context context, Handler handler, Executor executor, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
if (map != null) {
if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
sd = map.get(c);
}
if (sd == null) {
if (executor != null) {
sd = new ServiceDispatcher(c, context, executor, flags);
} else {
sd = new ServiceDispatcher(c, context, handler, flags);
}
if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
if (map == null) {
map = new ArrayMap<>();
mServices.put(context, map);
}
map.put(c, sd);
} else {
sd.validate(context, handler, executor);
}
return sd.getIServiceConnection();
}
}

4.2 AMS.publishService

1
2
3
4
5
6
7
8
9
10
public void publishService(IBinder token, Intent intent, IBinder service) {
synchronized(this) {
if (!(token instanceof ServiceRecord)) {
throw new IllegalArgumentException("Invalid service token");
}
// 调用 ActiveServices 的 publishServiceLocked() 方法
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}

4.3 AS.publishServiceLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {

if (r != null) {
Intent.FilterComparison filter = new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (b != null && !b.received) {
b.binder = service;
b.requested = true;
b.received = true;
// 从 ServiceRecord 的 connections 集合中取出数据
ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
for (int conni = connections.size() - 1; conni >= 0; conni--) {
ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
for (int i=0; i<clist.size(); i++) {
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
continue;
}
try {
// c.conn 为 IServiceConnection 对象
// 实际就是 LoadedApk.ServiceDispatcher.InnerConnection 类
c.conn.connected(r.name, service, false);
} catch (Exception e) {
//...
}
}
}
}

serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}

4.4 LA.ServiceDispatcher.InnerConnection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   // LoadedApk 内部类 InnerConnection 的 connected() 方法,也就是上面的 c.conn.connected() 方法  
private static class InnerConnection extends IServiceConnection.Stub {
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;

InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
}

public void connected(ComponentName name, IBinder service, boolean dead)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
// 调用 LoadedApk.ServiceDispatcher 的 connected() 方法
sd.connected(name, service, dead);
}
}
}

4.5 LA.ServiceDispatcher.connected

1
2
3
4
5
6
7
8
9
10
11
12
public void connected(ComponentName name, IBinder service, boolean dead) {
if (mActivityExecutor != null) {
mActivityExecutor.execute(new RunConnection(name, service, 0, dead));
} else if (mActivityThread != null) {
// 由 ContextImpl.bindServiceCommon() 方法中可知,mActivityThread 就是 ActivityThread 的 H 对象(主线程的Handler),不为null
// RunConnection 的 run方法中调用 doConnected() 方法
// 因为是通过主线程的 Handler 调用的方法,所以客户端的 ServiceConnection.onServiceConnected() 运行在主线程
mActivityThread.post(new RunConnection(name, service, 0, dead));
} else {
doConnected(name, service, dead);
}
}

4.6LA.ServiceDispatcher.RunConnection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private final class RunConnection implements Runnable {
RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
mName = name;
mService = service;
mCommand = command;
mDead = dead;
}

public void run() {
if (mCommand == 0) {
// 调用 doConnected() 方法
doConnected(mName, mService, mDead);
} else if (mCommand == 1) {
doDeath(mName, mService);
}
}

final ComponentName mName;
final IBinder mService;
final int mCommand;
final boolean mDead;
}

4.7 LA.ServiceDispatcher.doConnected

1
2
3
4
5
6
7
8
9
10
11
12
13
public void doConnected(ComponentName name, IBinder service, boolean dead) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;

//...
// 由 ContextImpl.bindServiceCommon() 方法中可知,mConnection 就是客户端的 ServiceConnection 对象,回调它的 onServiceConnected() 方法,完成绑定过程
if (service != null) {
mConnection.onServiceConnected(name, service);
} else {
// The binding machinery worked, but the remote returned null from onBind().
mConnection.onNullBinding(name);
}
}

mConnection 就是客户端的 ServiceConnection 对象,在前面 ContextImplbindServiceCommon() 方法说明时有注释进行说明了。

五、解绑 Service

图片来源于网络

六、停止 Service

图片来源于网络

startService启动过程分析

Android Service 流程分析

ActivityManagerService 通信浅析