盒子
盒子

Activity的创建流程

从startActivity开始分析

Activity.java:

1
2
3
4
5
6
7
8
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}

再进入到startActivityForResult方法:

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
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}

requestCode为返回码是当其大于等于0时会返回给onActivityResult,mParent是一个Activity类型的对象,指的是该Activity的父类,通过Manifest中设置android:parentActivityName属性来实现

1
2
3
4
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}

以下代码创建了一个ActivityResult类型的ar对象,并通过mMainThread.sendActivityResult发送该结果

1
2
3
4
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);

所以可以知道execStartActivity为该段代码的主要方法:

Instrumentation.java:

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
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
ActivityResult result = null;
if (am.ignoreMatchingSpecificIntents()) {
result = am.onStartActivity(intent);
}
if (result != null) {
am.mHits++;
return result;
} else if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManager.getService()
.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;
}

该段代码有两个主要方法:

1
2
3
4
5
6
7
result = am.onStartActivity(intent);

int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);

am.onStartActivity(intent)方法源码为:

1
2
3
public ActivityResult onStartActivity(Intent intent) {
return null;
}

所以ActivityManager.getService().startActivity才是要分析的主要方法:

1
protected private int startActivity(IApplicationThread var1, String var2, Intent var3, String var4, IBinder var5, String var6, int var7, int var8, ProfilerInfo var9, Bundle var10) throws RemoteException;

进入startActivity方法发现到了IActivityManager接口:

在IActivityManager接口中有一个内部类:

1
public abstract static class Stub extends Binder implements IActivityManager {...}

由此可以看出这是一个Binder

再看

1
public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {...}

即ActivityManagerService实现了IActivityManager接口中的startActivity方法

故这是通过Binder实现Instrumentation跨进程调用ActivityManagerService的startActivity方法

ActivityManagerService.java:

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());
}

继续跟着走,到最后一个startActivityAsUser方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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,
boolean validateIncomingUser) {
...
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}

由ActivityStartController类的obtainStarter方法:

1
2
3
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}

可知最终执行了ActivityStarter类中的execute方法,在该方法中进行了判断分别可调用startActivityMayWait和startActivity方法:

ActivityStarter。java - startActivit :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
} else {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
}

  • startActivityMayWait
  • 进入该方法发现会连续三个startActivity重载方法

  • startActivity
  • 直接进入第一个startActivity重载方法

    由以下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
    .setCaller(caller)
    .setCallingPackage(callingPackage)
    .setResolvedType(resolvedType)
    .setResultTo(resultTo)
    .setResultWho(resultWho)
    .setRequestCode(requestCode)
    .setStartFlags(startFlags)
    .setProfilerInfo(profilerInfo)
    .setActivityOptions(bOptions)
    .setMayWait(userId)
    .execute();

    的setMayWait方法:

    1
    2
    3
    4
    5
    ActivityStarter setMayWait(int userId) {
    mRequest.mayWait = true;
    mRequest.userId = userId;
    return this;
    }

    可知mRequest.mayWait为true故调用的是startActivityMayWait方法

    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
    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
    String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo,
    String resultWho, int requestCode, int callingPid,
    int callingUid,String callingPackage, int realCallingPid,
    int realCallingUid, int startFlags,SafeActivityOptions options,
    boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
    TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
    ......
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,true /* doResume */, checkedOptions, inTask, outActivity);
    }

    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
    ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
    mService.mWindowManager.deferSurfaceLayout();
    result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
    startFlags, doResume, options, inTask, outActivity);
    } finally {
    // If we are not able to proceed, disassociate the activity from the task. Leaving an
    // activity in an incomplete state can lead to issues, such as performing operations
    // without a window container.
    final ActivityStack stack = mStartActivity.getStack();
    if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
    stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
    null /* intentResultData */, "startActivity", true /* oomAdj */);
    }
    mService.mWindowManager.continueSurfaceLayout();
    }
    postStartActivityProcessing(r, result, mTargetStack);
    return result;
    }

    以上代码中的aInfo为节点中的信息,rInfo为对应的节点的信息

    在最后一个startActivity中调用了startActivityUnchecked方法,该方法中有两个创建Activity主要方法startActivityLocked 1439 和 resumeFocusedStackTopActivityLocked 1466

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
    if (mDoResume) {
    final ActivityRecord topTaskActivity =
    mStartActivity.getTask().topRunningActivityLocked();
    if (!mTargetStack.isFocusable()
    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
    && mStartActivity != topTaskActivity)) {
    mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    mService.mWindowManager.executeAppTransition();
    } else {
    if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
    mTargetStack.moveToFront("startActivityUnchecked");
    }
    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
    mOptions);
    }

    resumeFocusedStackTopActivityLocked将栈移到顶部

    进入到ActivityStackSupervisor类的resumeFocusedStackTopActivityLocked方法:

    ActivityStackSupervisor.java:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    boolean resumeFocusedStackTopActivityLocked(
    ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (!readyToResume()) {
    return false;
    }
    if (targetStack != null && isFocusedStack(targetStack)) {
    return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    if (r == null || !r.isState(RESUMED)) {
    mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    } else if (r.isState(RESUMED)) {
    // Kick off any lingering app transitions form the MoveTaskToFront operation.
    mFocusedStack.executeAppTransition(targetOptions);
    }
    return false;
    }

    经过如下判断会调用ActivityStack类中的resumeTopActivityUncheckedLocked方法

    1
    2
    3
    4
    5
    6
    if (r == null || !r.isState(RESUMED)) {
    mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    } else if (r.isState(RESUMED)) {
    // Kick off any lingering app transitions form the MoveTaskToFront operation.
    mFocusedStack.executeAppTransition(targetOptions);
    }

    在resumeTopActivityUncheckedLocked方法中会判断是否有Activity处于可见状态,及位于栈顶处于Resume状态,若存在则会将该Activity暂停即进入onPause状态
    ActivityStack.java:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    boolean resumeFocusedStackTopActivityLocked(
    ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    .......
    if (mResumedActivity != null) {
    if (DEBUG_STATES) Slog.d(TAG_STATES,
    "resumeTopActivityLocked: Pausing " + mResumedActivity);
    pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    ......
    }

    startPausingLocked很复杂会sendMessage到名为H的Handler中处理事件,最终调用onPause,故不深入追踪

    然后启动新Activity(ActivityStack类中resumeFocusedStackTopActivityLocked中的第2754行):

    1
    2
    3
    4
    5
    6
    7
    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ....
    //2723行
    mStackSupervisor.startSpecificActivityLocked(next, true, true);
    ....
    }

    ActivityStackSupervisor.java:

    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) {
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
    r.info.applicationInfo.uid, true);
    getLaunchTimeTracker().setLaunchTime(r);

    if (app != null && app.thread != null) {
    try {
    if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
    || !"android".equals(r.info.packageName)) {
    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
    mService.mProcessStats);
    }
    realStartActivityLocked(r, app, andResume, checkConfig);
    return;
    } catch (RemoteException e) {
    Slog.w(TAG, "Exception when starting activity "
    + r.intent.getComponent().flattenToShortString(), e);
    }
    }
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
    "activity", r.intent.getComponent(), false, false, true);
    }

    ActivityStackSupervisor是一个负责管理ActivityStack类的类

    在该方法中首先通过getProcessRecordLocked方法获得目标Activity所在的进程然后判断app是否已经启动,若启动则调用关键方法realStartActivityLocked:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
    boolean andResume, boolean checkConfig) throws RemoteException {
    ....
    // Create activity launch transaction.
    final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
    r.appToken);
    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
    System.identityHashCode(r), r.info,
    // TODO: Have this take the merged configuration instead of separate global
    // and override configs.
    mergedConfiguration.getGlobalConfiguration(),
    mergedConfiguration.getOverrideConfiguration(), r.compat,
    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
    profilerInfo));
    ....

    最后会便来到位于ActivityThread线程的LaunchActivityItem中的execute方法:

    此时便已经切换到了目标Activity进程

    此图来源于互联网:

    目标Activity进程流程图

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public void execute(ClientTransactionHandler client, IBinder token,
    PendingTransactionActions pendingActions) {
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
    mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
    mPendingResults, mPendingNewIntents, mIsForward,
    mProfilerInfo, client);
    // client是ActivityThread
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }

    来到ActivityThread中的handleLaunchActivity方法:

    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
    public Activity handleLaunchActivity(ActivityClientRecord r,
    PendingTransactionActions pendingActions, Intent customIntent) {
    // If we are getting ready to gc after going to the background, well
    // we are back active so skip it.
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    if (r.profilerInfo != null) {
    mProfiler.setProfiler(r.profilerInfo);
    mProfiler.startProfiling();
    }
    // Make sure we are running with the most recent config.
    handleConfigurationChanged(null, null);

    if (localLOGV) Slog.v(
    TAG, "Handling launch of " + r);

    // Initialize before creating the activity
    if (!ThreadedRenderer.sRendererDisabled) {
    GraphicsEnvironment.earlyInitEGL();
    }
    WindowManagerGlobal.initialize();
    final Activity a = performLaunchActivity(r, customIntent);
    ....
    }

    未完待续。。。。 - -

    支持一下
    扫一扫,支持Grooter
    • 微信扫一扫
    • 支付宝扫一扫