Android P ActivityManagerService(四) startActivity的第二小部分

下面是启动Activity进入AMS之后的部分流程;

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

找到AMS中的startActivity方法;

@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");

    // TODO: Switch to user app stacks here.
    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();

}

enforceNotIsolatedCaller("startActivity")是用来判断进程是否属于完全隔离的沙盒进程,此类进程没有自己的权限;

void enforceNotIsolatedCaller(String caller) {
    if (UserHandle.isIsolated(Binder.getCallingUid())) {
        throw new SecurityException("Isolated process not allowed to call " + caller);
    }
}

后面的两个方法都涉及到一个类ActivityStartController;先看一眼名词解释;

/**
 * Controller for delegating activity launches.
 *
 * This class' main objective is to take external activity start requests and prepare them into
 * a series of discrete activity launches that can be handled by an {@link ActivityStarter}. It is
 * also responsible for handling logic that happens around an activity launch, but doesn't
 * necessarily influence the activity start. Examples include power hint management, processing
 * through the pending activity list, and recording home activity launches.
 */
public class ActivityStartController

checkTargetUser是关于userId的一些操作,注释很详细;

/**
 * If {@code validateIncomingUser} is true, check {@code targetUserId} against the real calling
 * user ID inferred from {@code realCallingUid}, then return the resolved user-id, taking into
 * account "current user", etc.
 *
 * If {@code validateIncomingUser} is false, it skips the above check, but instead
 * ensures {@code targetUserId} is a real user ID and not a special user ID such as
 * {@link android.os.UserHandle#USER_ALL}, etc.
 */
int checkTargetUser(int targetUserId, boolean validateIncomingUser,
        int realCallingPid, int realCallingUid, String reason) {
    if (validateIncomingUser) {
        return mService.mUserController.handleIncomingUser(realCallingPid, realCallingUid,
                targetUserId, false, ALLOW_FULL_ONLY, reason, null);
    } else {
        mService.mUserController.ensureNotSpecialUser(targetUserId);
        return targetUserId;
    }
}

obtainStarter顾名思义,获取一个ActivityStarter;先看下ActivityStarter的名词解释;

/**
 * Controller for interpreting how and then launching an activity.
 *
 * This class collects all the logic for determining how an intent and flags should be turned into
 * an activity and associated task and stack.
 */
class ActivityStarter 

obtainStarter方法;

/**
 * @return A starter to configure and execute starting an activity. It is valid until after
 *         {@link ActivityStarter#execute} is invoked. At that point, the starter should be
 *         considered invalid and no longer modified or used.
 */
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

这里mFactory是ActivityStarter.Factory,它是一个接口;源码中详细的名词解释;

/**
 * An interface that to provide {@link ActivityStarter} instances to the controller. This is
 * used by tests to inject their own starter implementations for verification purposes.
 */
@VisibleForTesting
interface Factory {
    /**
     * Sets the {@link ActivityStartController} to be passed to {@link ActivityStarter}.
     */
    void setController(ActivityStartController controller);

    /**
     * Generates an {@link ActivityStarter} that is ready to handle a new start request.
     * @param controller The {@link ActivityStartController} which the starter who will own
     *                   this instance.
     * @return an {@link ActivityStarter}
     */
    ActivityStarter obtain();

    /**
     * Recycles a starter for reuse.
     */
    void recycle(ActivityStarter starter);
}

在ActivityStartController的构造函数中ActivityStarter.Factory被作为参数传入;

ActivityStartController(ActivityManagerService service) {
    this(service, service.mStackSupervisor,
            new DefaultFactory(service, service.mStackSupervisor,
                new ActivityStartInterceptor(service, service.mStackSupervisor)));
}

@VisibleForTesting
ActivityStartController(ActivityManagerService service, ActivityStackSupervisor supervisor,
        Factory factory) {
    mService = service;
    mSupervisor = supervisor;
    mHandler = new StartHandler(mService.mHandlerThread.getLooper());
    mFactory = factory;
    mFactory.setController(this);
    mPendingRemoteAnimationRegistry = new PendingRemoteAnimationRegistry(service,
            service.mHandler);
}

可以看到,实际传入的是ActivityStarter.DefaultFactory;看它的obtain方法;

@Override
public ActivityStarter obtain() {
    ActivityStarter starter = mStarterPool.acquire();

    if (starter == null) {
        starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
    }

    return starter;
}

果然也是没这么单纯的一个方法;出来的新面孔mStarterPool;它其实是一个对象池;

private SynchronizedPool<ActivityStarter> mStarterPool =
        new SynchronizedPool<>(MAX_STARTER_COUNT);

OK;下面看一下ActivityStarter中的execute方法;各种set就pass了;

/**
 * Starts an activity based on the request parameters provided earlier.
 * @return The starter result.
 */
int execute() {
    try {
        // TODO(b/64750076): Look into passing request directly to these methods to allow
        // for transactional diffs and preprocessing.
        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);
        }
    } finally {
        onExecutionComplete();
    }
}

这里分成一部分,一部分是startActivityMayWait,另一部分是startActivity;

最后会统一调用onExecutionComplete;

先看onExecutionComplete部分,再回过头来看start部分;

/**
 * Called when execution is complete. Sets state indicating completion and proceeds with
 * recycling if appropriate.
 */
private void onExecutionComplete() {
    mController.onExecutionComplete(this);
}

Controller部分代码;

void onExecutionComplete(ActivityStarter starter) {
    if (mLastStarter == null) {
        mLastStarter = mFactory.obtain();
    }

    mLastStarter.set(starter);
    mFactory.recycle(starter);
}

现在看start部分内容;此处先关注startActivity,startActivityMayWait以后再看;

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) {

    if (TextUtils.isEmpty(reason)) {
        throw new IllegalArgumentException("Need to specify a reason.");
    }
    mLastStartReason = reason;
    mLastStartActivityTimeMs = System.currentTimeMillis();
    mLastStartActivityRecord[0] = null;

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

    if (outActivity != null) {
        // mLastStartActivityRecord[0] is set in the call to startActivity above.
        outActivity[0] = mLastStartActivityRecord[0];
    }

    return getExternalResult(mLastStartActivityResult);
}

static int getExternalResult(int result) {
    // Aborted results are treated as successes externally, but we must track them internally.
    return result != START_ABORTED ? result : START_SUCCESS;
}

继续startActivity;此处的reason已经成被赋值给了mLastStartReason;所以新的startActivity无此参数;

这个方法有点长,看一眼就有些头晕,决定等下次看;

小结

ActivityStartController Controller for delegating activity launches.
This class' main objective is to take external activity start requests and prepare them into a series of discrete activity launches that can be handled by an {@link ActivityStarter}. It is also responsible for handling logic that happens around an activity launch, but doesn't necessarily influence the activity start. Examples include power hint management, processing through the pending activity list, and recording home activity launches.
用于委派活动启动的控制器;它的obtainStarter方法可以获取到一个ActivityStarter;
ActivityStarter

Controller for interpreting how and then launching an activity.
This class collects all the logic for determining how an intent and flags should be turned into an activity and associated task and stack..

也就是说,它完成了至关重要的一步 ;要intent和flags转换成了一个activity以及和这个activity相关的task和stack;

猜你喜欢

转载自blog.csdn.net/weixin_39821531/article/details/89393840