源码分析:Activity的启动过程(1)

Activity#startActivityForResult

我们从Activity的startActivity方法开始分析,该方法有几种重载方式,但最终都会调用startActivityForResult方法,该方法实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) { //只需关注这部分代码
//...

Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options); //先看Instrumentation的execStartActivity方法(exec是execute的缩写,意为执行)

//...
} else {
//...
}
}

我们看下Instrumentation的execStartActivity方法

Instrumentation#execStartActivity(API25)

  • Instrumentation类相当于一个管家,它的职责是管理各个应用程序和系统的交互,Instrumentation将在任何应用程序运行前初始化,每个进程只会存在一个Instrumentation对象,且每个Activity都有此对象的实际引用,可以通过它监测系统与应用程序之间的所有交互。
  • 这里可以看到真正启动Activity的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {

//...

try {
//...

//真正启动Activity
int result = ActivityManagerNative.getDefault() //ActivityManagerNative.getDefault()返回一个IActivityManager接口对象
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);

//检查启动结果,当无法正确启动时会抛出异常信息
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
  • 其中,IActivityManager接口的具体实现是ActivityManagerService(下面简称AMS)。AMS继承自ActivityManagerNative,而ActivityManagerNative继承自Binder并实现了IActivityManager,所以AMB也是一个Binder。不过在API26中,AMS不再继承AMN,而是继承IActivityManager.Stub。(注意:在API26中,AMN被弃用,其内部的代理类ActivityManagerProxy已经被删除。这是因为在API26启动Activity的时候,和AMS的通信机制已经被改成AIDL方式,详情请参考该博客

ActivityManagerNative.getDefault()

1
2
3
static public IActivityManager getDefault() {
return gDefault.get();
}

其中gDefault的定义如下:

1
2
3
4
5
6
7
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
IActivityManager am = asInterface(b);
return am;
}
};

Singleton是一个单例的封装类,第一次调用它的get方法时它会通过create方法来创建对象,在后续的调用中则直接返回之前创建的对象。

Instrumentation#execStartActivity(API26)

在API26中,真正启动Activity的代码发生了一些变化

1
2
3
4
5
6
//ActivityManager.getService()返回 IActivityManager对象
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);

ActivityManager.getService()

看下ActivityManager.getService()返回的是什么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
//其中,Context.ACTIVITY_SERVICE = "activity";
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};

可以看出,高低版本都是先获取服务端(系统进程)中的AMS的IBinder对象,然后通过得到的IBinder对象来生成IActivityManager(系统进程中的AMS在app进程中的binder代理)

ActivityManagerService#startActivity

虽然不同版本的实现有所不同,但最终都是返回IActivityManager接口对象,而IActivityManager接口的实现类为AMS,所以最终调用的是AMS的startActivity方法

1
2
3
4
5
6
7
8
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}

1
2
3
4
5
6
7
8
9
10
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
//...
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}
  • 其中mActivityStarter是一个ActivityStarter对象,ActivityStarter类主要负责处理Activity的Intent和Flags, 还有关联相关的Stack和TaskRecord。
  • 在API23及以前版本中,return那里是调用ActivityStackSupervisor的startActivityMayWait方法的(该方法的实现和ActivityStarter一样,不如说是ActivityStarter照搬该方法)
1
2
3
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, false, userId, null, null);

但是在API24中,ActivityStackSupervisor移除了startActivityMayWait方法,该方法到了ActivityStarter中。

又继续调用了几个方法

ActivityStarter#startActivityMayWait

  • startActivityMayWait: 根据Intent获取Activity的启动信息(ResolveInfo和ActivityInfo), 获取调用者的Pid和Uid(CallingPid和CallingUid)
  • startActivityMayWait继续调用startActivityLocked方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    //...
    int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
    aInfo, rInfo, voiceSession, voiceInteractor,
    resultTo, resultWho, requestCode, callingPid,
    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
    inTask);
    //...
    return res;

ActivityStarter#startActivityLocked

  • startActivityLocked: 创建ActivityRecord, 含有Activity的核心信息
  • startActivityLocked继续调用startActivityUnchecked方法
    1
    2
    3
    4
    5
    6
    7
    8
    //...
    try {
    //...
    err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
    true, options, inTask);
    }
    //...
    return err;

ActivityStarter#startActivityUnchecked

  • startActivityUnchecked:根据启动的Flag信息, 设置TaskRecord, 完成后执行ActivityStackSupervisor类的resumeFocusedStackTopActivityLocked方法, 继续启动。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    //...

    // 所有启动准备完成后, dontStart是true.
    final boolean dontStart = top != null && mStartActivity.resultTo == null
    && top.realActivity.equals(mStartActivity.realActivity)
    && top.userId == mStartActivity.userId
    && top.app != null && top.app.thread != null
    && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
    || mLaunchSingleTop || mLaunchSingleTask);
    if (dontStart) {
    //...
    if (mDoResume) {
    mSupervisor.resumeFocusedStackTopActivityLocked(); //mSupervisor是一个ActivityStackSupervisor对象
    }
    //...
    }

ActivityStackSupervisor和ActivityStack之间的相互跳转

ActivityStackSupervisor#resumeFocusedStackTopActivityLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}

boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
//targetStack是一个ActivityStack对象
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null); //mFocusedStack也是一个ActivityStack对象
}
return false;
}

又调用了ActivityStack的resumeTopActivityUncheckedLocked方法

ActivityStack#resumeTopActivityUncheckedLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}

boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
result = resumeTopActivityInnerLocked(prev, options); //调用resumeTopActivityInnerLocked方法
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}

最后返回的result的值是通过调用resumeTopActivityInnerLocked方法获得的

ActivityStack#resumeTopActivityInnerLocked

1
2
mStackSupervisor.startSpecificActivityLocked(next, true, false);    
//mStackSupervisor是一个ActivityStackSupervisor对象

又调用了ActivityStackSupervisor的startSpecificActivityLocked方法

ActivityStackSupervisor#startSpecificActivityLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);

r.task.stack.setLaunchTime(r);

if (app != null && app.thread != null) {
try {
//...

//真正启动activity的过程
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
//...
}

}

//...
}

终于,这里调用了realStartActivityLocked方法真正启动activity

API23及以前版本的一些区别

  • 在看《Android开发艺术探索》的时候,发现AMS的startActivityAsUser是调用ActivityStackSupervisor类的startActivityMayWait方法,这也导致后面一些方法调用的不同。

ActivityStackSupervisor#startActivityMayWait

这里的逻辑和API24版本是一样的,只不过调用的是ActivityStackSupervisor类的startActivityLocked方法

1
2
3
4
5
6
7
8
9
10
//...

int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho,
requestCode, callingPid, callingUid, callingPackage,
realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
componentSpecified, null, container, inTask);
//...

return res;

ActivityStackSupervisor#startActivityLocked

1
2
3
4
5
6
7
8
//...

err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);

//...

return err;

这里是又继续调用startActivityUncheckedLocked方法(和API24的名字不同,不过参数是一样的)

ActivityStackSupervisor#startActivityUncheckedLocked

1
2
3
4
5
6
7
8
9
10
//省略无关代码

if (doResume) {
targetStack.resumeTopActivityLocked(null, options);
}


if (doResume) {
targetStack.resumeTopActivityLocked(null); //targetStack是一个ActivityStack对象
}

又继续调用ActivityStack的resumeTopActivityLocked方法

ActivityStack#resumeTopActivityLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final boolean resumeTopActivityLocked(ActivityRecord prev) {
return resumeTopActivityLocked(prev, null);
}

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}

boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}

可以看出,该方法和API24以后的resumeTopActivityUncheckedLocked方法的实现是一样的,只是名字不同,而之后的调用就和API24以后一样了。

小结

  • 总的来说,从API24开始,在AMS(ActivityManagerService)与ASS(ActivityStackSupervisor)之间添加了一个ActivityStarter, 负责管理Activity的启动。

参考

-------------    本文到此结束  感谢您的阅读    -------------
0%