【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )

2023-03-29 14:14:39 浏览数 (1)

Android 插件化系列文章目录

【Android 插件化】插件化简介 ( 组件化与插件化 )

【Android 插件化】插件化原理 ( JVM 内存数据 | 类加载流程 )

【Android 插件化】插件化原理 ( 类加载器 )

【Android 插件化】“ 插桩式 “ 插件化框架 ( 原理与实现思路 )

【Android 插件化】“ 插桩式 “ 插件化框架 ( 类加载器创建 | 资源加载 )

【Android 插件化】“ 插桩式 “ 插件化框架 ( 注入上下文的使用 )

【Android 插件化】“ 插桩式 “ 插件化框架 ( 获取插件入口 Activity 组件 | 加载插件 Resources 资源 )

【Android 插件化】“ 插桩式 “ 插件化框架 ( 运行应用 | 代码整理 )

【Android 插件化】Hook 插件化框架 ( Hook 技术 | 代理模式 | 静态代理 | 动态代理 )

【Android 插件化】Hook 插件化框架 ( Hook 实现思路 | Hook 按钮点击事件 )

【Android 插件化】Hook 插件化框架 ( Hook Activity 启动过程 | 静态代理 )

【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 一 | Activity 进程相关源码 )

【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 二 | AMS 进程相关源码 | 主进程相关源码 )


文章目录

  • Android 插件化系列文章目录
  • 前言
  • 一、ActivityManagerService 进程相关源码
    • 1、ActivityManagerService 源码分析
    • 2、ActivityStarter 源码分析
      • a、obtainStarter 方法分析
      • b、execute 方法分析
      • c、startActivityMayWait 方法分析
      • d、startActivity 方法分析
      • e、startActivityUnchecked 方法分析
    • 3、ActivityStackSupervisor 源码分析
    • 4、ActivityStack 源码分析
      • a、resumeTopActivityUncheckedLocked 方法分析
      • b、resumeTopActivityInnerLocked 方法分析
      • c、startPausingLocked 方法分析
      • d、继续回到 resumeTopActivityInnerLocked 方法分析
    • 4、后续 ActivityStackSupervisor 源码分析
  • 二、ActivityThread 主进程相关源码
  • 三、博客资源

前言

上一篇博客 【Android 插件化】Hook 插件化框架 ( 从 Hook 应用角度分析 Activity 启动流程 一 | Activity 进程相关源码 ) 分析了 Activity 启动流程中 , Activity 进程中相关调用链涉及的源码 ;

本博客中着重分析 AMS 中涉及到的源码 和 AMS 启动主进程 Activity 源码 ;


一、ActivityManagerService 进程相关源码


1、ActivityManagerService 源码分析

在 Instrumentation 的 execStartActivity 方法中 , 最核心的代码是

代码语言:javascript复制
int result = ActivityTaskManager.getService().startActivity(whoThread,
        who.getBasePackageName(), who.getAttributionTag(), intent,
        intent.resolveTypeIfNeeded(who.getContentResolver()), token,
        target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);

先通过 ActivityTaskManager.getService() 获取服务 ,

代码语言:javascript复制
public class ActivityTaskManager {
    /** @hide */
    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    
    @UnsupportedAppUsage(trackingBug = 129726065)
    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };
}

调用 IActivityTaskManagerSingleton.get() 方法 , 就是调用 IActivityTaskManagerSingleton 的 create 方法 , 返回如下结果

代码语言:javascript复制
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);

该 IActivityTaskManager 没有找到对应 Java 代码 , 是 AIDL 文件 ; 返回的结果是 Binder 的代理类 , 该类主要作用是使用了 Binder 机制 , 进行进程间通信 ;

获取的远程服务是 ActivityManagerService , 在 Instrumentation 中调用 ActivityTaskManager.getService().startActivity() 方法 , 就是调用 AMS ( ActivityManagerService ) 的 startActivity 方法 , 最终调用的是 AMS 的 startActivityAsUser 方法 , 在该方法中调用了 ActivityStartController mActivityStartController 成员的 obtainStarter 方法 ,

代码语言:javascript复制
public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

	private final ActivityStartController mActivityStartController;

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

    }
}

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

2、ActivityStarter 源码分析

/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

a、obtainStarter 方法分析

调用 ActivityStartController 的 obtainStarter 方法 , 得到的是 ActivityStarter 方法 , Activity 的启动是由该 ActivityStarter 来完成的 ;

代码语言:javascript复制
public class ActivityStartController {
    /**
     * @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);
    }
}

b、execute 方法分析

Activity 启动过程很复杂 , 封装在 ActivityStarter 类中 , 该类有

2700

行代码 , 也是个重量级的类 , 因此没有在 ActivityManagerService 中定义 , 而是拆分出来 , 进行处理 ;

代码语言:javascript复制
class ActivityStarter {
    /**
     * 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();
        }
    }
}

c、startActivityMayWait 方法分析

如果需要等待 , 则调用 ActivityStarter 的 startActivityMayWait 方法 , 在该方法中需要获取调用的 进程 ID , 用户 ID ,

代码语言:javascript复制
        final int realCallingPid = Binder.getCallingPid();
        final int realCallingUid = Binder.getCallingUid();

然后 Activity 任务栈管理者 mSupervisor 解析 Intent , 将解析的信息放在 ResolveInfo rInfo 中 ;

代码语言:javascript复制
        ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                0 /* matchFlags */,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));

通过 Activity 任务栈管理者 mSupervisor 解析 Activity , 将获取的 Activity 信息放在 ActivityInfo aInfo 中 ;

代码语言:javascript复制
        // Collect information about the target of the Intent.
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

最后 , 调用 ActivityStarter 的 startActivity 方法 , 进行界面启动 ;

代码语言:javascript复制
            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);

d、startActivity 方法分析

ActivityStarter 中的 startActivity 方法参数较多 , 有十几个 ;

代码语言:javascript复制
    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);
}

在该方法的最后调用了 startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask, outActivity) 方法 ,

代码语言:javascript复制
    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
}

在上述参数较少的 startActivity 方法中 , 调用了 startActivityUnchecked 方法 ;

代码语言:javascript复制
    // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {

e、startActivityUnchecked 方法分析

在 ActivityStarter 中的 startActivityUnchecked 方法中 , 进行启动之前的初始化操作 , 如分析启动模式 LaunchMod , 解析设置的 Activity 启动标志位 Flag 等 ;

该方法中执行 Activity 启动前的操作 ;

代码语言:javascript复制
    // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor);

        computeLaunchingTaskFlags();

        computeSourceStack();

        mIntent.setFlags(mLaunchFlags);

        ActivityRecord reusedActivity = getReusableIntentActivity();
}

期间调用了 ActivityStarter 类的 private final ActivityStackSupervisor mSupervisor 成员的 resumeFocusedStackTopActivityLocked 方法 ;

代码语言:javascript复制
mSupervisor.resumeFocusedStackTopActivityLocked();

/frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

3、ActivityStackSupervisor 源码分析

ActivityStackSupervisor 的 resumeFocusedStackTopActivityLocked() 方法中 ,

调用了 boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) 方法 ,

在该方法中 , 判断当前的状态是否是 Resume 状态 , 如果不是 , 则调用 ActivityStack mFocusedStack 成员的 resumeTopActivityUncheckedLocked 方法 ;

代码语言:javascript复制
public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,
        RecentTasks.Callbacks {

    /** The stack currently receiving input or launching the next activity. */
    ActivityStack mFocusedStack;

    boolean resumeFocusedStackTopActivityLocked() {
        return resumeFocusedStackTopActivityLocked(null, null, null);
    }

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

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

4、ActivityStack 源码分析

a、resumeTopActivityUncheckedLocked 方法分析

上面分析到 Activity 调用 startActivity 调用的是 ActivityStack 的 resumeTopActivityUncheckedLocked 方法 , 在该方法中调用了 resumeTopActivityInnerLocked 方法 ;

代码语言:javascript复制
    /**
     * Ensure that the top activity in the stack is resumed.
     *
     * @param prev The previously resumed activity, for when in the process
     * of pausing; can be null to call from elsewhere.
     * @param options Activity options.
     *
     * @return Returns true if something is being resumed, or false if
     * nothing happened.
     *
     * NOTE: It is not safe to call this method directly as it can cause an activity in a
     *       non-focused stack to be resumed.
     *       Use {@link ActivityStackSupervisor#resumeFocusedStackTopActivityLocked} to resume the
     *       right activity for the current system state.
     */
    @GuardedBy("mService")
    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;
            result = resumeTopActivityInnerLocked(prev, options);

            // When resuming the top activity, it may be necessary to pause the top activity (for
            // example, returning to the lock screen. We suppress the normal pause logic in
            // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
            // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
            // to ensure any necessary pause logic occurs. In the case where the Activity will be
            // shown regardless of the lock screen, the call to
            // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
            if (next == null || !next.canTurnScreenOn()) {
                checkReadyForSleep();
            }
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }

        return result;
    }

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

b、resumeTopActivityInnerLocked 方法分析

在 ActivityStack 中的 resumeTopActivityInnerLocked 方法中调用了 startPausingLocked 方法 ;

代码语言:javascript复制
class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
        implements StackWindowListener {
    /** Run all ActivityStacks through this */
    protected final ActivityStackSupervisor mStackSupervisor;

    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing "   mResumedActivity);
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
	}
}

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

该方法的调用链很长 , 有几百行代码 ;

c、startPausingLocked 方法分析

startPausingLocked 方法中 , 调用了 mService.getLifecycleManager().scheduleTransaction 方法 , 该方法用于控制 Activity 声明周期的方法 , 其中涉及 PauseActivityItem 参数 , 说明要执行的是 Activity 的 onPause 生命周期方法 ;

代码语言:javascript复制
    /**
     * Start pausing the currently resumed activity.  It is an error to call this if there
     * is already an activity being paused or there is no resumed activity.
     *
     * @param userLeaving True if this should result in an onUserLeaving to the current activity.
     * @param uiSleeping True if this is happening with the user interface going to sleep (the
     * screen turning off).
     * @param resuming The activity we are currently trying to resume or null if this is not being
     *                 called as part of resuming the top activity, so we shouldn't try to instigate
     *                 a resume here if not null.
     * @param pauseImmediately True if the caller does not want to wait for the activity callback to
     *                         complete pausing.
     * @return Returns true if an activity now is in the PAUSING state, and we are waiting for
     * it to tell us when it is done.
     */
    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {
            
                mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                        PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));
                                
	}

注意 PauseActivityItem 专门用于处理 Activity Pause 生命周期 ;

/frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java

PauseActivityItem 继承了 ActivityLifecycleItem ,

/frameworks/base/core/java/android/app/servertransaction/ActivityLifecycleItem.java

ActivityLifecycleItem 继承了 ClientTransactionItem , ClientTransactionItem 会被 TransactionExecutor 执行 ,

/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

执行 PauseActivityItem 后 , 会自动调用 ActivityThread 主线程的 handlePauseActivity 方法 ;

/frameworks/base/core/java/android/app/ActivityThread.java

PauseActivityItem 的 execute 方法就是上述控制 onResume 生命周期函数触发的方法 ;

第一个参数 ClientTransactionHandler client , ActivityThread 继承了 ClientTransactionHandler 接口 , 这里的第一个参数是 ActivityThread 主线程 ;

此处调用的 ActivityThread 的 handlePauseActivity 方法 ;

代码语言:javascript复制
public class PauseActivityItem extends ActivityLifecycleItem {

    private static final String TAG = "PauseActivityItem";

    private boolean mFinished;
    private boolean mUserLeaving;
    private int mConfigChanges;
    private boolean mDontReport;

    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                "PAUSE_ACTIVITY_ITEM");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

d、继续回到 resumeTopActivityInnerLocked 方法分析

在 ActivityStack 中的 resumeTopActivityInnerLocked 方法中调用了 startPausingLocked 方法 , 其作用是触发上一个 Activity 的 Resume 生命周期 ;

在该 resumeTopActivityInnerLocked 方法的最后 , 调用了 ActivityStackSupervisor mStackSupervisor 成员的 startSpecificActivityLocked 方法 ;

代码语言:javascript复制
class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
        implements StackWindowListener {
    /** Run all ActivityStacks through this */
    protected final ActivityStackSupervisor mStackSupervisor;

    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing "   mResumedActivity);
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }

		mStackSupervisor.startSpecificActivityLocked(next, true, false);
	}
}

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

4、后续 ActivityStackSupervisor 源码分析

在 ActivityStackSupervisor 中的 startSpecificActivityLocked 方法中 , 调用的 realStartActivityLocked 方法是核心方法 , 在 realStartActivityLocked 方法中 , 获取到 LaunchActivityItem 后 , 传递给 clientTransaction , 去执行启动 Activity 的逻辑 ;

LaunchActivityItem 是要启动的目标 Activity ;

代码语言:javascript复制
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
            
                realStartActivityLocked(r, app, andResume, checkConfig);
    }

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

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

LaunchActivityItem 继承了 ClientTransactionItem , ClientTransactionItem 是 ActivityThread ;

/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java

在 LaunchActivityItem 中的 execute 方法 , 就是调用 ClientTransactionHandler client 参数的 handleLaunchActivity 方法 ;

其中 ClientTransactionHandler client 参数就是 ActivityThread ;

代码语言:javascript复制
public class LaunchActivityItem extends ClientTransactionItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java

二、ActivityThread 主进程相关源码


在 ActivityThread 的 handleLaunchActivity 方法中 , 在该方法中调用了 performLaunchActivity 方法 ;

代码语言:javascript复制
    /**
     * Extended implementation of activity launch. Used when server requests a launch or relaunch.
     */
    @Override
    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);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            if (!r.activity.mFinished && pendingActions != null) {
                pendingActions.setOldState(r.state);
                pendingActions.setRestoreInstanceState(true);
                pendingActions.setCallOnPostCreate(true);
            }
        } else {
            // If there was an error, for any reason, tell the activity manager to stop us.
            try {
                ActivityManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }

        return a;
    }

/frameworks/base/core/java/android/app/ActivityThread.java

在 performLaunchActivity 方法中调用了 Instrumentation 的 newActivity 方法 , 创建了一个新的 Activity 实例 ;

代码语言:javascript复制
public final class ActivityThread extends ClientTransactionHandler {
    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
		activity = mInstrumentation.newActivity(
		                    cl, component.getClassName(), r.intent);
	}
}

三、博客资源

博客资源 :

  • GitHub : https://github.com/han1202012/Plugin_Hook

0 人点赞