AMS_1

  • Post author:
  • Post category:其他




Activity启动流程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6JlfkUXU-1624238556945)(C:\Users\zl123\AppData\Roaming\Typora\typora-user-images\1624063652407.png)]

Launcher调用startActivity方法启动App,先经过AMS,如果App进程没有启动过,则AMS通过socket向Zygote通信,Zygote会fork出App进程。这时,会进入App进程执行,App通过attachApplication()方法,将IApplicationThread传给AMS,用于AMS和APP进程通信的客户端。App执行完后,会回到最初AMS启动App的地方执行,AMS控制App第一个Activity的启动。



Launcher->AMS

Activity.startActivity();

//Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}

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);
        //...
        cancelInputsAndStartExitTransition(options);
        // TODO Consider clearing/flushing other event sources and events for child windows.
    } else {
        //...
    }
}
//Instrumentation.java
public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, Activity target,
    Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    //...
    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;
}

//ActivityManager.java
public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}
//通过binder机制,返回AMS服务代理,通过调用代理方法,可以直接调用到AMS
private static final Singleton<IActivityManager> IActivityManagerSingleton =
    new Singleton<IActivityManager>() {
    @Override
    protected IActivityManager create() {
        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
        final IActivityManager am = IActivityManager.Stub.asInterface(b);
        return am;
    }
};



AMS阶段

//ActivityManagerService.java
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的重载,加入了userId,和一个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) {
    //...
    // 这个方法就是创建了ActivityStarter。并且调用了他的execute()方法
    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.Java
int execute() {
    try {
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                                        //...
                                        mRequest.allowPendingRemoteAnimationRegistryLookup);
        } else {
            return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                                 //...
                                 mRequest.allowPendingRemoteAnimationRegistryLookup);
        }
    } finally {
        onExecutionComplete();
    }
}

private int startActivityMayWait(IApplicationThread caller, int callingUid,
                                 //...
                                 boolean allowPendingRemoteAnimationRegistryLookup) {
    //...
    // Save a copy in case ephemeral needs it
    final Intent ephemeralIntent = new Intent(intent);
    // Don't modify the client's object!
    intent = new Intent(intent);
    //...

    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId... ))
        // Collect information about the target of the Intent.
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    //...
    final ActivityRecord[] outRecord = new ActivityRecord[1];
    int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                            //...
                            allowPendingRemoteAnimationRegistryLookup);
    //...
    return res;

}

//在startActivityMayWait方法中调用startActivity经过重载(其中一个startActivity方法中new了ActivityRecord)后,调到这个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();
        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;
    }
}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    //处理一些Activity启动模式相关的操作
    //...
    if (mDoResume) {
        mSupervisor.resumeFocusedStackTopActivityLocked();
    }
    //...
     mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
    //...
}

//ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked() {
    return resumeFocusedStackTopActivityLocked(null, null, null);
}

boolean resumeFocusedStackTopActivityLocked(
    ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

  //...
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }

    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.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    //...
    boolean result = false;
    try {
        // Protect against recursion.
        mStackSupervisor.inResumeTopActivity = true;
        result = resumeTopActivityInnerLocked(prev, options);
       //...
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}

 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
      if (next.app != null && next.app.thread != null) {
          //不需要重新启动
      }else{
          //需要重新启动
          mStackSupervisor.startSpecificActivityLocked(next, true, true);
      }
 }

//ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                                                        r.info.applicationInfo.uid, true);
    getLaunchTimeTracker().setLaunchTime(r);
	//如果待启动Activity的进程已经存在
    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                || !"android".equals(r.info.packageName)) {
                // Don't add this if it is a platform component that is marked
                // to run in multiple processes, because this is actually
                // part of the framework so doesn't make sense to track as a
                // separate apk in the process.
                app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                               mService.mProcessStats);
            }
            //调用realStartActivityLocked。如果待启动Activity的进程不存在,会走启动zygote fork新进程流程,走app进程ActivityThread main方法,在绑定application流程中,在完成Application初始化,绑定后,回到AMS,AMS也会调用该方法,启动第一个activity。
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                   + r.intent.getComponent().flattenToShortString(), e);
        }

        // If a dead object exception was thrown -- fall through to
        // restart the application.
    }

    //如果待启动Activity的进程不存在,调用ActivityManagerService的startProcessLocked方法启动进程
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                                "activity", r.intent.getComponent(), false, false, true);
}




启动新进程流程

//ActivityManagerService.java
//经过一些列重载调用到这个startProcessLocked
private final boolean startProcessLocked(ProcessRecord app, String hostingType,//...
                                        ) {
    //...
    final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
                        uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                        invokeWith, startTime);
    //...
}

private ProcessStartResult startProcess(String hostingType, String entryPoint,
                                        /
                                        long startTime) {
    try {
        //判断是否是webview_service
        if (hostingType.equals("webview_service")) {
            startResult = startWebView(entryPoint,
                                       //...
                                       new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        } else {
            startResult = Process.start(entryPoint,
                                         //...
                                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        }
        checkTime(startTime, "startProcess: returned from zygote!");
        return startResult;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

//Process.java
public static final ProcessStartResult start(final String processClass,
                                             //...
                                             String[] zygoteArgs) {
    return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                               runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                               abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}

//ZygoteProcess.java
public final Process.ProcessStartResult start(final String processClass,
                                              //...
                                              String[] zygoteArgs) {
    try {
        return startViaZygote(processClass, niceName, uid, gid, gids,
                              runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                              abi, instructionSet, appDataDir, invokeWith, false,
                              zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        //..
    }
}

private Process.ProcessStartResult startViaZygote(final String processClass,
                                                  //...
                                                  String[] extraArgs)
    throws ZygoteStartFailedEx {
    ArrayList<String> argsForZygote = new ArrayList<String>();
    // --runtime-args, --setuid=, --setgid=,
    // and --setgroups= must go first
    argsForZygote.add("--runtime-args");
    //...
    synchronized(mLock) {
        //开启ZygoteSocket,通过Socket进行通信
        return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
    }
}

经过上面流程,就会fork出新进程,并且调用ActivityThread的main方法;T



ActivityThread main流程

//ActivityThread .java
//成员变量,直接初始化,就是提供AMS与App通信的客户端
final ApplicationThread mAppThread = new ApplicationThread();
public static void main(String[] args) {
    //...
    //创建主线程Looper
    Looper.prepareMainLooper();
    //...
    //创建ActivityThread,并且调用attach方法,传入false,如果是系统启动流程,调用systemMain,传入true
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                                            LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    // ...
    //启动looper
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        //...
        //获取AMS并调用attachApplication方法,传入mAppThread,较给AMS,作为AMS和App通信的客户端
        final IActivityManager mgr = ActivityManager.getService();
        try {
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        // Watch for getting close to heap limit.
        //...
    } else {
        //系统启动流程,调用systemMain,传入true
    }

    // add dropbox logging to libcore
    //...
}

//ActivityManagerService.java
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        //这里会做binder身份校验
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
    //...
    //通过IApplicationThread thread,再调回到app进程。
    if (app.isolatedEntryPoint != null) {
        // This is an isolated process which should just call an entry point instead of
        // being bound to an application.
        thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
    } else if (app.instr != null) {
        thread.bindApplication(processName, appInfo, providers,
                               app.instr.mClass,
                               profilerInfo, app.instr.mArguments,
                               app.instr.mWatcher,
                               app.instr.mUiAutomationConnection, testMode,
                               mBinderTransactionTrackingEnabled, enableTrackAllocation,
                               isRestrictedBackupMode || !normalMode, app.persistent,
                               new Configuration(getGlobalConfiguration()), app.compat,
                               getCommonServicesLocked(app.isolated),
                               mCoreSettingsObserver.getCoreSettingsLocked(),
                               buildSerial, isAutofillCompatEnabled);
    } else {
        thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                               null, null, null, testMode,
                               mBinderTransactionTrackingEnabled, enableTrackAllocation,
                               isRestrictedBackupMode || !normalMode, app.persistent,
                               new Configuration(getGlobalConfiguration()), app.compat,
                               getCommonServicesLocked(app.isolated),
                               mCoreSettingsObserver.getCoreSettingsLocked(),
                               buildSerial, isAutofillCompatEnabled);
    }
    
    
    //...
    //走完bindApplication流程后,会继续回到attachApplicationLocked函数。继而走到这里
    mStackSupervisor.attachApplicationLocked(app)
}

//ActivityStackSupervisor.java
//执行到这个方法说明 thread.bindApplication这个流程已经结束
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    //...
    //调用realStartActivityLocked。启动第一个activity
    if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
        didSomething = true;
    }
    //..
}

//ActivityThread.java-ApplicationThread
public final void bindApplication(String processName, ApplicationInfo appInfo,
                                  L//...
                                  String buildSerial, boolean autofillCompatibilityEnabled) {

    
    if (services != null) {
       //...
        // Setup the service cache in the ServiceManager
        ServiceManager.initServiceCache(services);
    }

    setCoreSettings(coreSettings);
	//因为binder机制,AMS段调用该方法,使得改方法在子线程执行。所以要通过handler将消息发送到主线程处理
    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providers;
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
    data.instrumentationWatcher = instrumentationWatcher;
    data.instrumentationUiAutomationConnection = instrumentationUiConnection;
    data.debugMode = debugMode;
    data.enableBinderTracking = enableBinderTracking;
    data.trackAllocation = trackAllocation;
    data.restrictedBackupMode = isRestrictedBackupMode;
    data.persistent = persistent;
    data.config = config;
    data.compatInfo = compatInfo;
    data.initProfilerInfo = profilerInfo;
    data.buildSerial = buildSerial;
    data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
    sendMessage(H.BIND_APPLICATION, data);
}
//ActivityThread.java
//成员H继承hanlder
final H mH = new H();
//内部类H
class H extends Handler {
    public static final int BIND_APPLICATION        = 110;
    //...

    public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        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;
                //...
        }
        Object obj = msg.obj;
        if (obj instanceof SomeArgs) {
            ((SomeArgs) obj).recycle();
        }
        if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
    }
}

private void handleBindApplication(AppBindData data) {
    // Register the UI Thread as a sensitive thread to the runtime.
    VMRuntime.registerSensitiveThread();
    //...
    //创建一个Instrumentation
    //获取LoadedApk对象  getPackageInfo 创建LoadedApk对象,并将将新创建的LoadedApk加入到mPackages. 也就是说每个app都会创建唯一的LoadedApk对象
    // Continue loading instrumentation.
    if (ii != null) {
        ApplicationInfo instrApp;
        try {
            instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
                                                              UserHandle.myUserId());
        } catch (RemoteException e) {
            instrApp = null;
        }
        if (instrApp == null) {
            instrApp = new ApplicationInfo();
        }
        ii.copyTo(instrApp);
        instrApp.initForUser(UserHandle.myUserId());
        final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                                            appContext.getClassLoader(), false, true, false);
        final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);

        try {
            final ClassLoader cl = instrContext.getClassLoader();
            mInstrumentation = (Instrumentation)
                cl.loadClass(data.instrumentationName.getClassName()).newInstance();
        } catch (Exception e) {
            throw new RuntimeException(
                "Unable to instantiate instrumentation "
                + data.instrumentationName + ": " + e.toString(), e);
        }

        final ComponentName component = new ComponentName(ii.packageName, ii.name);
        mInstrumentation.init(this, instrContext, appContext, component,
                              data.instrumentationWatcher, data.instrumentationUiAutomationConnection);

        if (mProfiler.profileFile != null && !ii.handleProfiling
            && mProfiler.profileFd == null) {
            mProfiler.handlingProfiling = true;
            final File file = new File(mProfiler.profileFile);
            file.getParentFile().mkdirs();
            Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
        }
    } else {
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    }
   
    
    Application app;
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
    final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
    //通过LoadApk的makeApplication创建Application
    app = data.info.makeApplication(data.restrictedBackupMode, null);
    //...

    mInitialApplication = app;

    
    if (!data.restrictedBackupMode) {
        if (!ArrayUtils.isEmpty(data.providers)) {
            //如果有ContentProvider,则先初始化ContentProvider
            installContentProviders(app, data.providers);
            mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
        }
    }

    //空实现
    mInstrumentation.onCreate(data.instrumentationArgs);
    //调用Application的onCreat方法
    mInstrumentation.callApplicationOnCreate(app);
	
}



创建Application流程

//LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
                                   Instrumentation instrumentation) {
    if (mApplication != null) {
        return mApplication;
    }

    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");

    Application app = null;

    String appClass = mApplicationInfo.className;
    if (forceDefaultAppClass || (appClass == null)) {
        appClass = "android.app.Application";
    }

    try {
        //创建ClassLoader
        java.lang.ClassLoader cl = getClassLoader();
        if (!mPackageName.equals("android")) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                             "initializeJavaContextClassLoader");
            initializeJavaContextClassLoader();
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
        //获取AppContext
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        //创建Application对象
        app = mActivityThread.mInstrumentation.newApplication(
            cl, appClass, appContext);
        appContext.setOuterContext(app);
    } catch (Exception e) {
        //...
    }
    mActivityThread.mAllApplications.add(app);
    mApplication = app;

    if (instrumentation != null) {
        try {
            instrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
           //...
        }
    }
    //...

    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    return app;
}

//Instrumentation.java
public Application newApplication(ClassLoader cl, String className, Context context)
    throws InstantiationException, IllegalAccessException, 
ClassNotFoundException {
    //最后就是反射创建
    Application app = getFactory(context.getPackageName())
        .instantiateApplication(cl, className);
    app.attach(context);
    return app;
}

//Application.java
final void attach(Context context) {
    attachBaseContext(context);
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

protected void attachBaseContext(Context base) {
    if (mBase != null) {
        throw new IllegalStateException("Base context already set");
    }
    mBase = base;
}



realStartActivityLocked流程

//ActivityStackSupervisor.java
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添加了LaunchActivityItem的callBack,后面会用到
    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                                                            System.identityHashCode(r), r.info,
                                                            //..
                                                            profilerInfo));

    // Set desired final state.
    final ActivityLifecycleItem lifecycleItem;
    if (andResume) {
        lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
    } else {
        lifecycleItem = PauseActivityItem.obtain();
    }
    clientTransaction.setLifecycleStateRequest(lifecycleItem);

    // Schedule transaction.
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    //...
}

//ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //就是和app进程通信,调用到app进程。执行ApplicationThread的scheduleTransaction方法.???
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        // If client is not an instance of Binder - it's a remote call and at this point it is
        // safe to recycle the object. All objects used for local calls will be recycled after
        // the transaction is executed on client in ActivityThread.
        transaction.recycle();
    }
}


//ApplicationThread.java
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

//ActivityThread.java

//ActivityThread成员 执行多步骤事务的执行器。
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

class H extends Handler {
    public static final int EXECUTE_TRANSACTION = 159;
    //...

    public void handleMessage(Message msg) {
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
        switch (msg.what) {
            case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                //执行TransactionExecutor的execute方法传入ClientTransaction
                mTransactionExecutor.execute(transaction);
                if (isSystem()) {
                    transaction.recycle();
                }
                break;
                //...
        }
        Object obj = msg.obj;
        if (obj instanceof SomeArgs) {
            ((SomeArgs) obj).recycle();
        }
        if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
    }
}


//TransactionExecutor.java
public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
    executeCallbacks(transaction);
    executeLifecycleState(transaction);
    mPendingActions.clear();
    log("End resolving transaction");
}

public void executeCallbacks(ClientTransaction transaction) {
    //获取ClientTransaction中之前在realStartActivityLocked过程中存的callbacks,泛型是ClientTransactionItem,其实是LaunchActivityItem对象。
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    //...
    final IBinder token = transaction.getActivityToken();
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    //...
    final int size = callbacks.size();
    //遍历callbacks,取出来执行execute方法。
    for (int i = 0; i < size; ++i) {
        //...
        //这里执行的是LaunchActivityItem的execute方法
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
        //...
    }
}

//LaunchActivityItem.java
public class LaunchActivityItem extends ClientTransactionItem {
    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);
        //执行ClientTransactionHandler的handleLaunchActivity方法,正好ActivityThread继承了ClientTransactionHandler,其实是执行ActivityThread的handleLaunchActivity方法
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

//ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
    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;
    }
}
 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;
}

}




版权声明:本文为weixin_47259048原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。