导航号,我的单页导航
文章目录

前言

简单记录一下startActivity()源码的启动过程,主要是过一下流程,细节太多顾不上。

下面以Launcher界面启动(startActivity())未启动过的应用为例。

这部分主要涉及,启动新的Activity前,系统会让当前Activity[叫Launcher吧]进入onPause()流程。

PS :(1) 简单记录,不一定对 (2) Android P

正文

在Launcher界面启动Media应用,启动代码如下

Intent intent = new Intent();
intent.setPackage("com.biumall.media");
intent.setComponent(new ComponentName("com.biumall.media", "com.biumall.media.MediaActivity"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Activity.java

startActivity()
@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}
startActivity()
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    //options == null
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        //注意,两个参数
        startActivityForResult(intent, -1);
    }
}
startActivityForResult()

两个参数的

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
    startActivityForResult(intent, requestCode, null);
}
startActivityForResult()

三个参数的

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    // mParent == null 
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        // 走这里
        // 调用Instrumentation.execStartActivity()
        // 存在两个,只是第四个参数不一样,注意
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        // ar等于null 
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        // 传入的为-1
        if (requestCode >= 0) {
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
    } else {
        //略
    }
}

Instrumentation.java

execStartActivity()
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    //略
    //mActivityMonitors为null
    if (mActivityMonitors != null) {
        //略
    }
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        //调用的ActivityManagerService.startActivity()
        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;
}

ActivityManagerService.java

startActivity()
startActivityAsUser()
startActivityAsUser()

三个放一起了,

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

@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) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
            true /*validateIncomingUser*/);
}

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) {
    enforceNotIsolatedCaller("startActivity");
    userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    //suerid = 0
    //调用ActivityStarter.execue(),
    //具体看obtainStarter()的返回值,
    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();
}

重点,调用的是ActivityStarter.execue(),上用build模式进行初始化参数。

ActivityStarter.java
execute()
int execute() {
    //setMayWait(userId)给mayWait设置true
    try {
        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 {
            //略
        }
    } finally {
        onExecutionComplete();
    }
}
startActivityMayWait()
private int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, Intent intent, String resolvedType,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, WaitResult outResult,
        Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
        int userId, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup) {
	//略
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 ,computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));	
	//rInfo不为null
    if (rInfo == null) {
		//略
    }
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    synchronized (mService) {
        final ActivityStack stack = mSupervisor.mFocusedStack;
        stack.mConfigWillChange = globalConfig != null
                && mService.getGlobalConfiguration().diff(globalConfig) != 0;
        final long origId = Binder.clearCallingIdentity();
		//aInfo不为null,但后面的不满足
        if (aInfo != null &&
                (aInfo.applicationInfo.privateFlags
                        & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0 &&
                mService.mHasHeavyWeightFeature) {
			//略
        }
        final ActivityRecord[] outRecord = new ActivityRecord[1];
		//[重]进入startActivity
        int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                allowPendingRemoteAnimationRegistryLookup);

        Binder.restoreCallingIdentity(origId);
		//false
        if (stack.mConfigWillChange) {
			//略
        }
		// outResult 为null,
        if (outResult != null) {
			//略
        }
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
        return res;
    }
}
startActivity()
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, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup) {
	//略
	//[重]startActivity
	//mLastStartActivityResult = 0 表示成功
    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
            aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
            callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
            options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
            inTask, allowPendingRemoteAnimationRegistryLookup);
	//outActivity不等于null
    if (outActivity != null) {
        outActivity[0] = mLastStartActivityRecord[0];
    }
    return getExternalResult(mLastStartActivityResult);
}
startActivity()
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) {
    int err = ActivityManager.START_SUCCESS;
    final Bundle verificationBundle
            = options != null ? options.popAppVerificationBundle() : null;
    ProcessRecord callerApp = null;
	//caller不为null
    if (caller != null) {
        callerApp = mService.getRecordForAppLocked(caller);
		//调用者Pid和UI,也就是启动Activity的应用的
        if (callerApp != null) {
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
	//略,细节不关心,直接看下面
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
            true /* doResume */, checkedOptions, inTask, outActivity);
}
startActivity()
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();
		//r是启动Activity的信息
		//[重]进入startActivityUnchecked
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        final ActivityStack stack = mStartActivity.getStack();
		//stack不为null, result=0
        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;
}
startActivityUnchecked()
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {
	//略
	//不为null,packageName就是启动的包名
    if (mStartActivity.packageName == null) {
		//略
        return START_CLASS_NOT_FOUND;
    }
	//略
	//dontStart 为false
	if (dontStart) {
		//略
        return START_DELIVERED_TO_TOP;
    }
	//略
	//mDoResume为true
    if (mDoResume) {
		Slog.e(TAG, "startActivityUnchecked(24) start topRunningActivityLocked : ");
        final ActivityRecord topTaskActivity =
                mStartActivity.getTask().topRunningActivityLocked();
		//mTargetStack.isFocusable()为true
		// mStartActivity== topTaskActivity,都是启动Activity
		if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
				//略
        } else {
            if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
			//[重]resumeFocusedStackTopActivityLocked
            mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                    mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    }
    mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
    mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
            preferredLaunchDisplayId, mTargetStack);
    return START_SUCCESS;
}

ActivityStackSupervisor.java

resumeFocusedStackTopActivityLocked()
boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
	//readyToResume()为true
    if (!readyToResume()) {
        return false;
    }
	//targetStack不为null,isFocusedStack()为true
	if (targetStack != null && isFocusedStack(targetStack)) {
		//[重]走这里
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
	//略
    return false;
}

ActivityStack.java

resumeTopActivityUncheckedLocked()
@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
	// false,所以不进入这里,走下面
	if (mStackSupervisor.inResumeTopActivity) {
        return false;
    }
    boolean result = false;
    try {
        mStackSupervisor.inResumeTopActivity = true;
		//进入这里
        result = resumeTopActivityInnerLocked(prev, options);
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
		//next不等于null, next.canTurnScreenOn()= false
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}
resumeTopActivityInnerLocked()
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	//mBooting = false, mBooted = true
	if (!mService.mBooting && !mService.mBooted) {
        return false;
    }
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
	//next不为null
    final boolean hasRunningActivity = next != null;
	// hasRunningActivity = true, isAttached() = true
	if (hasRunningActivity && !isAttached()) {
        return false;
    }
    mStackSupervisor.cancelInitializingActivities();
    boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;
	//hasRunningActivity 为true
    if (!hasRunningActivity) {
        return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities");
    }
	//略
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(next);
	//略
	mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
	//略
	//[重],这回先暂停上一个activity
	//也就是Launcher的Activity进入Pause周期
	//进入pauseBackStacks()分析
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
	// mResumedActivity 为 null,不进入
    if (mResumedActivity != null) {
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
	//pausing = true , resumeWhilePausing = false 进入
    if (pausing && !resumeWhilePausing) {
		//符合条件[Skip resume: need to start pausing]
        if (next.app != null && next.app.thread != null) {
            mService.updateLruProcessLocked(next.app, true, null);
        }
        if (lastResumed != null) {
            lastResumed.setWillCloseOrEnterPip(true);
        }
        return true;
    } else if (mResumedActivity == next && next.isState(RESUMED)
            && mStackSupervisor.allResumedActivitiesComplete()) {
        executeAppTransition(options);
        return true;
    }
	//略
	//上面退出去了,这里暂时不走,后面会走这里
    return true;
}

ActivityStackSupervisor.java

pauseBackStacks()
boolean pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait) {
	//userLeaving=true
	//resuming 需要启动的Activity
	//dontWait false
    boolean someActivityPaused = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!isFocusedStack(stack) && stack.getResumedActivity() != null) {
				//从Launcher界面启动,此时Activity处于resume周期,需要pause
                someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming,
                        dontWait);
            }
        }
    }
	// true
    return someActivityPaused;
}

ActivityStack.java

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
        ActivityRecord resuming, boolean pauseImmediately) {
    // mPausingActivity = null
    if (mPausingActivity != null) {
        if (!shouldSleepActivities()) {
            completePauseLocked(false, resuming);
        }
    }
    ActivityRecord prev = mResumedActivity;
	//prev 不为null,就是Launcher的Activity
    if (prev == null) {
        if (resuming == null) {
            mStackSupervisor.resumeFocusedStackTopActivityLocked();
        }
        return false;
    }
	//resuming 启动的Activity,不相等
    if (prev == resuming) {
        return false;
    }
    mPausingActivity = prev;
    mLastPausedActivity = prev;
    mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
            || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
    prev.setState(PAUSING, "startPausingLocked");
    prev.getTask().touchActiveTime();
    clearLaunchTime(prev);
    mStackSupervisor.getLaunchTimeTracker().stopFullyDrawnTraceIfNeeded(getWindowingMode());
    mService.updateCpuStats();
	//prev是Launcher的Activity信息,满足下面条件
    if (prev.app != null && prev.app.thread != null) {
        try {
            EventLogTags.writeAmPauseActivity(prev.userId, System.identityHashCode(prev),
                    prev.shortComponentName, "userLeaving=" + userLeaving);
            mService.updateUsageStats(prev, false);
			//[重] mService.getLifecycleManager() 应该获取的是。。。。
            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                    PauseActivityItem.obtain(prev.finishing, userLeaving,
                            prev.configChangeFlags, pauseImmediately));
        } catch (Exception e) {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
    } else {
        mPausingActivity = null;
        mLastPausedActivity = null;
        mLastNoHistoryActivity = null;
    }
    if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
        mStackSupervisor.acquireLaunchWakelock();
    }
	//mPausingActivity不为null,上面赋值了
    if (mPausingActivity != null) {
		//uiSleeping = false
        if (!uiSleeping) {
            prev.pauseKeyDispatchingLocked();
        } else if (true) {
             Slog.v(TAG, "Key dispatch not paused for screen off");
        }
		//pauseImmediately =  false
        if (pauseImmediately) {
            completePauseLocked(false, resuming);
            return false;
        } else {
			//这里返回
            schedulePauseTimeout(prev);
            return true;
        }

    } else {
		//略
        return false;
    }
}

上面的关注点是

  1. 调用了ClientLifecycleManager.scheduleTransaction()

  2. 第三个参数是PauseActivityItem对象

mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
      PauseActivityItem.obtain(prev.finishing, userLeaving,
          prev.configChangeFlags, pauseImmediately));

ClientLifecycleManager.java

scheduleTransaction()

三个参数的

void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
        @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
    //通过transactionWithState()创建了clientTransaction对象
    //stateRequest就是传入的PauseActivityItem对象
    //[1]
    final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
            stateRequest);
    //[2]
    scheduleTransaction(clientTransaction);
}
transactionWithState()
private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
        @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
    final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
    //stateRequest就是传入的PauseActivityItem对象
    clientTransaction.setLifecycleStateRequest(stateRequest);
    return clientTransaction;
}
scheduleTransaction()
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    //调用schedule()
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}

ClientTransaction.java

schedule()
public void schedule() throws RemoteException {
	//mClient是一个IApplicationThread类型,
	//ActivityThread的内部类ApplicationThread派生这个接口类并实现了对应的方法。
    mClient.scheduleTransaction(this);
}

ActivityThread.java

scheduleTransaction()
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
	//调用的是ActivityThread的方法,但没有实现
	//子债父还,找父类ClientTransactionHandler
    ActivityThread.this.scheduleTransaction(transaction);
}

ClientTransactionHandler.java

ClientTransactionHandler是个抽象类,部分方法实现需要看子类。

scheduleTransaction()
void scheduleTransaction(ClientTransaction transaction) {
	//ClientTransaction调用preExecute
	//这里不太懂[暂时略过]
    transaction.preExecute(this);
	//子类ActivityThread实现,发送EXECUTE_TRANSACTION
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

ActivityThread.java

sendMessage()
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);
}
handleMessage()
public void handleMessage(Message msg) {
        switch (msg.what) {
            case BIND_APPLICATION:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                AppBindData data = (AppBindData)msg.obj;
                handleBindApplication(data);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
			//略
            case EXECUTE_TRANSACTION: 
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                //[重]
                mTransactionExecutor.execute(transaction);
                if (isSystem()) {
                    transaction.recycle();
                }
                break;
        }
        Object obj = msg.obj;
        if (obj instanceof SomeArgs) {
            ((SomeArgs) obj).recycle();
        }
    }
}

TransactionExecutor.java

execute()
public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    //略过
    executeCallbacks(transaction);
    //重点关注
    executeLifecycleState(transaction);
    mPendingActions.clear();
}
executeLifecycleState()
private void executeLifecycleState(ClientTransaction transaction) {
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
	//不为null,是PauseActivityItem对象
    if (lifecycleItem == null) {
        return;
    }
    final IBinder token = transaction.getActivityToken();
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
	//不等于null,这里指的Launcher的Activity
    if (r == null) {
        return;
    }
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
	//PauseActivityItem对象,execute
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
	//PauseActivityItem对象,postExecute
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}

PauseActivityItem.java

这里先附上

execute()
@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
	//client是ActivityThread对象
    client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
            "PAUSE_ACTIVITY_ITEM");
}
postExecute()
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    //mDontReport=false
    if (mDontReport) {
        return;
    }
    try {
		//执行ActivityManagerService.activityPaused
        ActivityManager.getService().activityPaused(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

先分析execute(),后分析postExecute(),这里单独分开,后面再回到这里哈。

ActivityThread.java

先分析上面execute()中调用的

handlePauseActivity()
@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    ActivityClientRecord r = mActivities.get(token);
    //r不为null
    if (r != null) {
    	// true
        if (userLeaving) {
            performUserLeavingActivity(r);
        }
        r.activity.mConfigChangeFlags |= configChanges;
		//finished = false
		//reason = PAUSE_ACTIVITY_ITEM
        performPauseActivity(r, finished, reason, pendingActions);
		//r.isPreHoneycomb() false
        if (r.isPreHoneycomb()) {
            QueuedWork.waitToFinish();
        }
        mSomeActivitiesChanged = true;
    }
}
performPauseActivity()
final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
    ActivityClientRecord r = mActivities.get(token);
    return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
}
performPauseActivity()
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
	//r.paused false 还没启动完,肯定还没暂停成功
    if (r.paused) {
    	//略
    }
	//false
    if (finished) {
        r.activity.mFinished = true;
    }
    final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
	//false
    if (shouldSaveState) {
        callActivityOnSaveInstanceState(r);
    }
    //执行pause
    performPauseActivityIfNeeded(r, reason);
	//略
    return shouldSaveState ? r.state : null;
}
performPauseActivityIfNeeded()
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
	//此时没有暂停
    if (r.paused) {
        return;
    }
    try {
        r.activity.mCalled = false;
        //[重]这里call暂停
        mInstrumentation.callActivityOnPause(r.activity);
	   //略
    } catch (SuperNotCalledException e) {
    	//略
    }
    r.setState(ON_PAUSE);
}

Instrumentation.java

callActivityOnPause()
public void callActivityOnPause(Activity activity) {
    activity.performPause();
}

activity是Launcher的Activity,也就是当前界面

Activity.java

performPause()
final void performPause() {
    mDoReportFullyDrawn = false;
    mFragments.dispatchPause();
    mCalled = false;
    //执行onPause()周期
    onPause();
    writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
    //这个标志之前有用过,判断是否在前台还是后台
    mResumed = false;
    if (!mCalled && getApplicationInfo().targetSdkVersion
            >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPause()");
    }
}

至此,Launcher的Activity进入后台了,也就执行了onPause()周期。

我们返回上面postExecute()分析,调用的是

 //ActivityManagerService.activityPaused()
 ActivityManager.getService().activityPaused(token);

ActivityManagerService.java

activityPaused()
@Override
public final void activityPaused(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized(this) {
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        // stack 不为null
        if (stack != null) {
            stack.activityPausedLocked(token, false);
        }
    }
    Binder.restoreCallingIdentity(origId);
}

ActivityStack.java

activityPausedLocked()
final void activityPausedLocked(IBinder token, boolean timeout) {
    final ActivityRecord r = isInStackLocked(token);
	//r不为null,也就是Launcher的Activity
    if (r != null) {
        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
		//相等
        if (mPausingActivity == r) {
            mService.mWindowManager.deferSurfaceLayout();
            try {
				//表示完成paused状态
                completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
            } finally {
                mService.mWindowManager.continueSurfaceLayout();
            }
            //这里直接返回了
            return;
        } else {
		   //略
        }
    }
    //略
}
completePauseLocked()
private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
    ActivityRecord prev = mPausingActivity;
    //pre就是暂停的Activity
    if (prev != null) {
		//略
    }
	//传入的是true
    if (resumeNext) {
        final ActivityStack topStack = mStackSupervisor.getFocusedStack();
        if (!topStack.shouldSleepOrShutDownActivities()) {
			//[重1]
            mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
        } else {
			//略
        }
    }
	//略
    if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
            || getDisplay().hasPinnedStack()) {
        mService.mTaskChangeNotificationController.notifyTaskStackChanged();
        mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
    }
    //[重2]
    mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
}

ActivityStackSupervisor.java

resumeFocusedStackTopActivityLocked()

这个方法之前走过的,又回来了。

boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
	//readyToResume() 为true
    if (!readyToResume()) {
        return false;
    }
	//targetStack不为null; isFocusedStack()为true,因此进入
	if (targetStack != null && isFocusedStack(targetStack)) {
		//走这里
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
	//略
    return false;
}

ActivityStack.java

resumeTopActivityUncheckedLocked()
@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
	// false
	if (mStackSupervisor.inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        mStackSupervisor.inResumeTopActivity = true;
		//进入这里
        result = resumeTopActivityInnerLocked(prev, options);
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
		//next不等于null,next.canTurnScreenOn()= false
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}
resumeTopActivityInnerLocked()
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	//mBooting = false, mBooted = true
	if (!mService.mBooting && !mService.mBooted) {
        return false;
    }
	//next不为null,也就是启动的Activity
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
	//略
	//上面进入过一次,只不过是暂停Launcher的Activity,
	//此时Launcher的Activity进入onPause()
	//因此这里返回false,pausing= false
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
	// mResumedActivity为null
    if (mResumedActivity != null) {
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
	//pausing为false,此时mResumedActivity为null
    if (pausing && !resumeWhilePausing) {
		//略
        return true;
    } else if (mResumedActivity == next && next.isState(RESUMED)
		//略
        return true;
    }
	//略
	//prev是上一个Launcher的Activity
	//next是将启动的Activity
    if (prev != null && prev != next) {
        if (!mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(prev)
                && next != null && !next.nowVisible) {
			//进入这里
            mStackSupervisor.mActivitiesWaitingForVisibleActivity.add(prev);
        } else {
			//略
        }
    }

    // Launching this app's activity, make sure the app is no longer
    // considered stopped.
    try {
	    //设置启动包名为停止状态,上面有英文注释
        AppGlobals.getPackageManager().setPackageStoppedState(
                next.packageName, false, next.userId); /* TODO: Verify if correct userid */
    } catch (RemoteException e1) {
		//略
	}
	//prev 不为null
    if (prev != null) {
		// prev.finishing = false
        if (prev.finishing) {
            //略
        } else {
            if (mStackSupervisor.mNoAnimActivities.contains(next)) {
                anim = false;
                mWindowManager.prepareAppTransition(TRANSIT_NONE, false);
            } else {
				//走这里,准备app转换过度吧
                mWindowManager.prepareAppTransition(prev.getTask() == next.getTask()
                        ? TRANSIT_ACTIVITY_OPEN
                        : next.mLaunchTaskBehind
                                ? TRANSIT_TASK_OPEN_BEHIND
                                : TRANSIT_TASK_OPEN, false);
            }
        }
    } else {
		//略
    }
	// anim 为true
    if (anim) {
        next.applyOptionsLocked();
    } else {
        next.clearOptionsLocked();
    }
	//略
	//next还没启动,因此为null
    if (next.app != null && next.app.thread != null) {
		//略,如果之前启动过,会走这里
    } else {
		// next.hasBeenLaunched 为false
        if (!next.hasBeenLaunched) {
            next.hasBeenLaunched = true;
        } else {
			//略
        }
		//走这里
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}

ActivityStackSupervisor.java

startSpecificActivityLocked()
void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
	//通过包名进行获取进程记录
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
    getLaunchTimeTracker().setLaunchTime(r);
	// pp为null,因为还没启动过呢
    if (app != null && app.thread != null) {
		//略
    }
	//启动进程。
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

ActivityManagerService.java

startProcessLocked()
@GuardedBy("this")
final ProcessRecord startProcessLocked(String processName,
        ApplicationInfo info, boolean knownToBeDead, int intentFlags,
        String hostingType, ComponentName hostingName, boolean allowWhileBooting,
        boolean isolated, boolean keepIfLarge) {
    return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
            hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
            null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
            null /* crashHandler */);
}
startProcessLocked()
@GuardedBy("this")
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
        boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
        String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    long startTime = SystemClock.elapsedRealtime();
    ProcessRecord app;
	//false
    if (!isolated) {
        app = getProcessRecordLocked(processName, info.uid, keepIfLarge);

        checkTime(startTime, "startProcess: after getProcessRecord");

        if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
			//略
        } else {
            mAppErrors.resetProcessCrashTimeLocked(info);
            if (mAppErrors.isBadProcessLocked(info)) {
				//略
            }
        }
    } else {
        app = null;
    }
	//app=null, pid=-1
    if (app != null && app.pid > 0) {
		//略
    }
    String hostingNameStr = hostingName != null
            ? hostingName.flattenToShortString() : null;
    if (app == null) {
        checkTime(startTime, "startProcess: creating new process record");
		//创建新的ProcessRecord
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
		//不为null
        if (app == null) {
            return null;
        }
        app.crashHandler = crashHandler;
        app.isolatedEntryPoint = entryPoint;
        app.isolatedEntryPointArgs = entryPointArgs;
        checkTime(startTime, "startProcess: done creating new process record");
    } else {
        app.addPackage(info.packageName, info.versionCode, mProcessStats);
        checkTime(startTime, "startProcess: added package to existing proc");
    }
	//mProcessesReady true
    if (!mProcessesReady
            && !isAllowedWhileBooting(info)
            && !allowWhileBooting) {
           
        if (!mProcessesOnHold.contains(app)) {
            mProcessesOnHold.add(app);
        }
        checkTime(startTime, "startProcess: returning with proc on hold");
        return app;
    }
    checkTime(startTime, "startProcess: stepping in to startProcess");
	// success = true
	//正常情况下,都会创建成功,具体略过,有兴趣的可以跟哈
    final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
    checkTime(startTime, "startProcess: done starting proc!");
    return success ? app : null;
}

至此,正常情况下app,最后在startProcessLocked()下面调用startProcess(),后面懒得跟了。

最后新的进程启动和绑定等下回介绍哈。

说实话,确实很绕,晕头转向的。

参考文章

© 版权声明
导航号,我的单页导航

暂无评论

暂无评论...