回顾

先简略的回顾一下,在Android中,第一个敞开的是init进程,它解析了init.rc文件,发动各种service:zygote,surfaceflinger,service_manager。接着就讲了Zygote,Zygote便是一个孵化器,它敞开了system_server以及敞开了ZygoteServer用来接收客户端的恳求,当客户端恳求来了之后就会fork出来子进程,而且初始化binder进程信息,为了加速Zygote还会预加载一些classDrawablecolor等体系资源。接下来讲了system_server,它是体系发动办理service入口,比方AMSPMSWMS等等,它加载了framework-res.apk,接着调用startBootstrapService,startCoreService,startOtherService敞开十分多的服务,还敞开了WatchDog,来监控service。接着讲了service_manager,他是一个独立的进程,它存储了体系各种服务的Binder,咱们常常经过ServiceMananger来获取,其间还详细说了Binder机制,C/S架构,大家要记住客户端BinderServer三端的工作流程。之后讲了Launcher,它由system_server发动,经过LauncherModel进行Binder通讯 经过PMS来查询一切的运用信息,然后绑定到RecyclerView中,它的点击事情是经过ItemClickHandler来处理。接着讲了AMS是怎样敞开运用进程的,首要咱们从Launcher的点击开始,调用到ActivitystartActivity函数,经过InstrumentationexecStartActivity经过两次IPC(1.经过ServiceManager获取到ATMS 2.调用ATMS的startActivity) 调用到AMS端在AMS端进行了一系列的信息处理,会判别进程是否存在,没有存在的话就会敞开进程(经过Socket,给ZygoteServer发送信息),传入entryPointActivityThread,经过Zygotefork出来子进程(运用进程)调用ActivityThread.main,运用进程创立之后会调用到AMS,由AMSattachApplication存储进程信息,然后告知客户端,让客户端来创立Application,并在客户端创立成功之后 持续履行敞开Activity的流程。客户端接收到AMS的数据之后会创立loadedApk,Instrumentation 以及Application调用attach(attachBaseContext),调用InstrumentationcallApplicationOncreate履行ApplicationOncreate周期。

详细的细节能够参考之前写的文章和视频:

【Android FrameWork】第一个发动的程序–init

【Android FrameWork】Zygote

【Android FrameWork】SystemServer

【Android FrameWork】ServiceManager(一)

【Android FrameWork】ServiceManager(二)

【Android Framework】Launcher3

【Android Framework】ActivityManagerService(一)

介绍

之前咱们介绍了AMS是怎样敞开进程的,这次咱们就接着之前的内容往下走,看看在创立Application之后,是怎样敞开Activity的。

正文

  1. Activity的发动 之前讲了进程的发动,现在咱们来看看进程发动之后是怎样发动Activity的。首要让咱们回到AMS,当ActivityThread创立之后会告知AMS进行attachApplication

private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    //根据pid获取到app信息
    app = mPidsSelfLocked.get(pid);
    //thread指的是ActivityThread 所以这儿是IPC通讯
    thread.bindApplication(processName, appInfo, providers,
        instr2.mClass,
        profilerInfo, instr2.mArguments,
        instr2.mWatcher,
        instr2.mUiAutomationConnection, testMode,
        mBinderTransactionTrackingEnabled, enableTrackAllocation,
        isRestrictedBackupMode || !normalMode, app.isPersistent(),
        new Configuration(app.getWindowProcessController().getConfiguration()),
        app.compat, getCommonServicesLocked(app.isolated),
        mCoreSettingsObserver.getCoreSettingsLocked(),
        buildSerial, autofillOptions, contentCaptureOptions);
//从starting applications中移除
mPersistentStartingProcesses.remove(app);
    if (normalMode) {
        try {
        //发动activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }
    return true;
}

调用mAtmInternalattachApplication

public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
    synchronized (mGlobalLockWithoutBoost) {
        return mRootActivityContainer.attachApplication(wpc);
    }
}
boolean attachApplication(WindowProcessController app) throws RemoteException {
    //获取到进程名 也便是包名
    final String processName = app.mName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.get(displayNdx);
        final ActivityStack stack = display.getFocusedStack();
        if (stack != null) {
            //从mTaskHistory后往前找activity 只要咱们之前insert的Activity
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            //从前台stack栈顶获取没有finsish 的Activity
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                //假如Activity 没运行 而且uid共同  进程名共同
                if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                    //敞开activity
                        if (mStackSupervisor.realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisible(null, 0, false /* preserve_windows */);
    }
    return didSomething;
}

调用了RootActivityContainer.javaattachApplication,进行一些信息判别,然后履行StackSupervisorrealStartActivityLocked

//WindowProcessController 用来和AMS的ProcessRecord进行通讯,当ProcessRecord中对应运用进程做出修正之后经过他来和WM进行通讯
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
        boolean andResume, boolean checkConfig) throws RemoteException {
    //判别是否都暂停成功
    if (!mRootActivityContainer.allPausedActivitiesComplete()) {
        return false;
    }
    //根据activity 获取到taskRecord
    final TaskRecord task = r.getTaskRecord();
    //获取到ActivityStack
    final ActivityStack stack = task.getStack();
    //resume引证++
    beginDeferResume();
    try {
        r.startFreezingScreenLocked(proc, 0);
        r.startLaunchTickingLocked();
        //设置WPC
        r.setProcess(proc);
        if (andResume && !r.canResumeByCompat()) {
            andResume = false;
        }
          //launchCount++ 记载发动次数
        r.launchCount++;
        //记载发动时刻
        r.lastLaunchTime = SystemClock.uptimeMillis();
        //增加activity到WPC
        proc.addActivityIfNeeded(r);
        try {
            //创立ClientTransaction 用来和客户端通讯 客户端收到后履行对应的业务
            final ClientTransaction clientTransaction = ClientTransaction.obtain(
            //client为当时运用进程 以及apptoken
                    proc.getThread(), r.appToken);
            //获取到DisplayContent 屏幕显现设备
            final DisplayContent dc = r.getDisplay().mDisplayContent;
            //增加callback 这个会触发onCreate
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                    r.icicle, r.persistentState, results, newIntents,
                    dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                            r.assistToken));
             //创立ActivityLifecycleItem 决定履行resume仍是pause
            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {//这儿为true
            //设置为on_resume 
                lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            //设置状况恳求为resume
            clientTransaction.setLifecycleStateRequest(lifecycleItem);    
 //履行业务           mService.getLifecycleManager().scheduleTransaction(clientTransaction);
        } catch (RemoteException e) {
        }
    } finally {
        endDeferResume();
    }
    r.launchFailed = false;
    if (stack.updateLRUListLocked(r)) {
    }
    if (andResume && readyToResume()) {
        stack.minimalResumeActivityLocked(r);
    } else {
        r.setState(PAUSED, "realStartActivityLocked");
    }
    //oom相关 更新进程的状况信息
    proc.onStartActivity(mService.mTopProcessState, r.info);
    if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
        mService.getActivityStartController().startSetupActivity();
    }
    //更新关怀的服务
    if (r.app != null) {
        r.app.updateServiceConnectionActivities();
    }
    return true;
}

realStartActivityLocked中 判别Activity是否都暂停成功,而且创立ClientTransaction增加LaunchActivityItem用来和客户端通讯。咱们看看是怎样履行的使命。 首要阐明下ClientTransactionHandler,它是用来处理AMSActivity的整个生命周期的类,而且ActivityThread继承自它。 ClientTransaction是一系列客户端处理的业务,客户端取出业务履行,例如LaunchActivityItemResumeActivityItem等。ClientLifecycleManager是客户端办理生命周期履行。

所以在AMS设置完信息之后,调用ClientLifecycleManagerscheduleTransaction

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}
文件目录:/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
//这儿的mClient便是咱们的运用进程ActivityThread
    mClient.scheduleTransaction(this);
}
//ActivityThread中 履行的是父类的
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}
//履行ClientTransactionHandler的scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
    //履行客户端业务之前需求处理的业务
    transaction.preExecute(this);
    //发送音讯给mH履行EXECUTE_TRANSACTION
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//发送音讯给mH
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);
}
看看怎样处理的这个音讯.
case EXECUTE_TRANSACTION:
    //拿到ClientTransaction
    final ClientTransaction transaction = (ClientTransaction) msg.obj;
    //调用TransactionExecutor(长途业务的履行者)履行业务
    mTransactionExecutor.execute(transaction);
    if (isSystem()) {
        transaction.recycle();
    }
    break;
    //在这儿履行业务
public void execute(ClientTransaction transaction) {
    //拿到binder
    final IBinder token = transaction.getActivityToken();
    //履行业务 LaunchActivityItem
    executeCallbacks(transaction);
    //履行状况
    executeLifecycleState(transaction);
    //清空actions
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}
//履行业务 也便是LauncherActivityItem的履行 
public void executeCallbacks(ClientTransaction transaction) {
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    //没有callback 回来 咱们是有callback的便是LauncherActivityItem
    if (callbacks == null || callbacks.isEmpty()) {
        // No callbacks to execute, return early.
        return;
    }
    final IBinder token = transaction.getActivityToken();
    //获取到ActivityClientRecord 获取到客户端的ActivityRecord
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        //履行item的execute item便是LaunchActivityItem
        item.execute(mTransactionHandler, token, mPendingActions);
        //调用postExecute
        item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }
}
//execute 获取到ActivityClientRecord
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client, mAssistToken);
      //调用ActivityThread的handleLaunchActivity
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    mSomeActivitiesChanged = true;
    //初始化WMG 之后说WMS的时分在介绍 和window 页面相关的
    WindowManagerGlobal.initialize();
    //调用performLaunchActivity
    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 {
    }
    return a;
}
//创立Activity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //拿到ActivityInfo
    ActivityInfo aInfo = r.activityInfo;
    //拿到component
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }
    //根据ActivityClientRecord来创立activity context 
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        //获取到类加载器 也便是咱们app的类加载器 PathCalssLoader
        java.lang.ClassLoader cl = appContext.getClassLoader();
        //经过mInstrumentation的newActivity  反射创立Activity 
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
    }
    try {
        //获取app
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        if (activity != null) {
            //创立Configuration 屏幕大小 屏幕方向 和一些配置的信息
            Configuration config = new Configuration(mCompatConfiguration);
            if (r.overrideConfig != null) {
                config.updateFrom(r.overrideConfig);
            }
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
            //设置OuterContext
            appContext.setOuterContext(activity);
            //调用activity的attach window相关
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback,
                    r.assistToken);
            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            checkAndBlockForNetworkAccess();
            activity.mStartedActivity = false;
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }
            activity.mCalled = false;
            //履行mInstrumentation的callActivityOncreate
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
        }
            r.activity = activity;
        }
        //设置状况为ON_CREATE
        r.setState(ON_CREATE);
        synchronized (mResourcesManager) {
            //存入map
            mActivities.put(r.token, r);
        }
    } catch (SuperNotCalledException e) {
    } catch (Exception e) {
    }
    return activity;
}
//Instrumentation的newActivity
public Activity newActivity(ClassLoader cl, String className,
        Intent intent)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {
    String pkg = intent != null && intent.getComponent() != null
            ? intent.getComponent().getPackageName() : null;
    return getFactory(pkg).instantiateActivity(cl, className, intent);
}
//反射创立Activity 回来
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
        @Nullable Intent intent)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Activity) cl.loadClass(className).newInstance();
}
//调用Activity的attach 为Activity关联上下文环境
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
        //调用attachBaseContext
    attachBaseContext(context);
    //履行fragments的attach
    mFragments.attachHost(null /*parent*/);
    //创立PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
        mWindow.setSoftInputMode(info.softInputMode);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }
   //设置ui线程
    mUiThread = Thread.currentThread();
    //设置mainThread
    mMainThread = aThread;
   //设置Instrumentation
    mInstrumentation = instr;
    mToken = token;
    mAssistToken = assistToken;
    mIdent = ident;
    mApplication = application;
    mIntent = intent;
    mReferrer = referrer;
    mComponent = intent.getComponent();
    mActivityInfo = info;
    mTitle = title;
    mParent = parent;
    mEmbeddedID = id;
    mLastNonConfigurationInstances = lastNonConfigurationInstances;
    if (voiceInteractor != null) {
        if (lastNonConfigurationInstances != null) {
            mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
        } else {
            mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                    Looper.myLooper());
        }
    }
    mWindow.setWindowManager(
            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    mCurrentConfig = config;
    mWindow.setColorMode(info.colorMode);
    setAutofillOptions(application.getAutofillOptions());
    setContentCaptureOptions(application.getContentCaptureOptions());
}
//履行activity的OnCreate
public void callActivityOnCreate(Activity activity, Bundle icicle) {
//从waitActivities中移除
    prePerformCreate(activity);
    //履行Activity的生命周期OnCreate
    activity.performCreate(icicle);
    //监控ActivityMonitor
    postPerformCreate(activity);
}
final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
//回调Activity的监听onActivityPreCreated 例如在Application中注册了
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    //调用onCreate
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    mActivityTransitionState.readState(icicle);
    a
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    //Fragments的分发
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    //回调Activity的监听post
    dispatchActivityPostCreated(icicle);
}
//便是咱们复写的onCreate
protected void onCreate(@Nullable Bundle savedInstanceState) {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
    if (mLastNonConfigurationInstances != null) {
        mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
    }
    if (mActivityInfo.parentActivityName != null) {
        if (mActionBar == null) {
            mEnableDefaultActionBarUp = true;
        } else {
            mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
        }
    }
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                View.LAST_APP_AUTOFILL_ID);
        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    dispatchActivityCreated(savedInstanceState);
    if (mVoiceInteractor != null) {
        mVoiceInteractor.attachActivity(this);
    }
    mRestoredFromBundle = savedInstanceState != null;
    mCalled = true;
}

回到ActivityThreadscheduleTransaction来履行业务,给mH发送EXECUTE_TRANSACTION履行,调用TransactionExecutor来履行,主要是两个函数executeCallbacks来履行LauncherActivityItem,它会调用InstrumentationnewActivity反射创立Activity 以及ActivityContext以及设置window相关信息,调用InstrumentationcallActivityOnCreate履行Applicaiton监听的Activity创立的回调,以及ActivityOnCreate函数。此刻现已将状况设置为ON_CREATE。接着会调用executeLifecycleState,咱们看看他做了什么?

private void executeLifecycleState(ClientTransaction transaction) {
//咱们之前在这儿设置了ResumeActivityItem
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        return;
    }
    final IBinder token = transaction.getActivityToken();
    //获取到ActivityClientRecord
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
     //lifecycleItem是ResumeActivityItem 它的targetState是ON_RESUME
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
        ClientTransaction transaction) {
        //获取到当时状况是ON_CREATE
    final int start = r.getLifecycleState();
    //数组里边存储的是2
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    //履行lifecyleSequence
    performLifecycleSequence(r, path, transaction);
}
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    mLifecycleSequence.clear();
    if (finish >= start) {//当时start是1 finish是3 
        for (int i = start + 1; i <= finish; i++) {
            //增加2和3
            mLifecycleSequence.add(i);
        }
    } else { // finish < start, can't just cycle down
        if (start == ON_PAUSE && finish == ON_RESUME) {
            // Special case when we can just directly go to resumed state.
            mLifecycleSequence.add(ON_RESUME);
        } else if (start <= ON_STOP && finish >= ON_START) {
            // Restart and go to required state.
            // Go to stopped state first.
            for (int i = start + 1; i <= ON_STOP; i++) {
                mLifecycleSequence.add(i);
            }
            // Restart
            mLifecycleSequence.add(ON_RESTART);
            // Go to required state
            for (int i = ON_START; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        } else {
            // Relaunch and go to required state
            // Go to destroyed state first.
            for (int i = start + 1; i <= ON_DESTROY; i++) {
                mLifecycleSequence.add(i);
            }
            // Go to required state
            for (int i = ON_CREATE; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        }
    }
    //删除最后一个3
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }
    return mLifecycleSequence;
}
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
        ClientTransaction transaction) {
    final int size = path.size();//size = 2
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        switch (state) {
            case ON_START://2
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            case ON_RESUME://3
                mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                        r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                break;
        }
    }
}
//处理startActivity
public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    final Activity activity = r.activity;
    //履行onStart 分发fragments的onStart 以及监听函数的履行
    activity.performStart("handleStartActivity");
    //设置状况为ON_START
    r.setState(ON_START);
//履行onRestoreInstanceState
    if (pendingActions.shouldRestoreInstanceState()) {
        if (r.isPersistable()) {
            if (r.state != null || r.persistentState != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                        r.persistentState);
            }
        } else if (r.state != null) {
            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
        }
    }
//履行onPostCreate
    if (pendingActions.shouldCallOnPostCreate()) {
        activity.mCalled = false;
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnPostCreate(activity, r.state,
                    r.persistentState);
        } else {
            mInstrumentation.callActivityOnPostCreate(activity, r.state);
        }
    }
}
final void performStart(String reason) {
    //分发pre start
    dispatchActivityPreStarted();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    mFragments.noteStateNotSaved();
    mCalled = false;
    mFragments.execPendingActions();
    //调用Activity的onStart
    mInstrumentation.callActivityOnStart(this);
    //fragments分发start
    mFragments.dispatchStart();
    mFragments.reportLoaderStart();
    boolean isAppDebuggable =
            (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
    if (isAppDebuggable || isDlwarningEnabled) {
        String dlwarning = getDlWarning();
        if (dlwarning != null) {
            String appName = getApplicationInfo().loadLabel(getPackageManager())
                    .toString();
            String warning = "Detected problems with app native libraries\n" +
                             "(please consult log for detail):\n" + dlwarning;
            if (isAppDebuggable) {//是否debug
                  new AlertDialog.Builder(this).
                      setTitle(appName).
                      setMessage(warning).
                      setPositiveButton(android.R.string.ok, null).
                      setCancelable(false).
                      show();
            } else {
            }
        }
    }
    GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
    mActivityTransitionState.enterReady(this);
    //履行post回调
    dispatchActivityPostStarted();
}
//履行activity的onStart
public void callActivityOnStart(Activity activity) {
    activity.onStart();
}
//Activity的onStart
protected void onStart() {
    mCalled = true;
       //分发Fragments
    mFragments.doLoaderStart();
    //分发监听
    dispatchActivityStarted();
    if (mAutoFillResetNeeded) {
        getAutofillManager().onVisibleForAutofill();
    }
}
//履行activity的onPostCreate
public void callActivityOnPostCreate(@NonNull Activity activity,
        @Nullable Bundle savedInstanceState,
        @Nullable PersistableBundle persistentState) {
    activity.onPostCreate(savedInstanceState, persistentState);
}
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    if (!isChild()) {
        mTitleReady = true;
        //更新title
        onTitleChanged(getTitle(), getTitleColor());
    }
    mCalled = true;
    notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
}

履行executeCallbacks之后设置状况为ON_START,在executeLifecycleState中获取到start(ON_CREATE)finsih(ON_RESUME),所以path的值为2,履行performLifecycleSequence会调用mTransactionHandler.handleStartActivity。接着回调用item.execute便是ResumeActivityItemexecute

//调用到ActivityThread的handleResumeActivity
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
            "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
        //调用performResumeActivity
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    final Activity a = r.activity;
    final int forwardBit = isForward
            ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
    boolean willBeVisible = !a.mStartedActivity;
      //第一次来是null所以会创立window
    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();
        decor.setVisibility(View.INVISIBLE);
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
        l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
        l.softInputMode |= forwardBit;
        if (r.mPreserveWindow) {
            a.mWindowAdded = true;
            r.mPreserveWindow = false;
            ViewRootImpl impl = decor.getViewRootImpl();
            if (impl != null) {
                impl.notifyChildRebuilt();
            }
        }
        if (a.mVisibleFromClient) {
            if (!a.mWindowAdded) {
                a.mWindowAdded = true;
                wm.addView(decor, l);
            } else {
                a.onWindowAttributesChanged(l);
            }
        }
    } else if (!willBeVisible) {
        r.hideForNow = true;
    }
    cleanUpPendingRemoveWindows(r, false /* force */);
    if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
        if (r.newConfig != null) {
            performConfigurationChangedForActivity(r, r.newConfig);
            }
            r.newConfig = null;
        }
        WindowManager.LayoutParams l = r.window.getAttributes();
        if ((l.softInputMode
                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                != forwardBit) {
            l.softInputMode = (l.softInputMode
                    & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
                    | forwardBit;
            if (r.activity.mVisibleFromClient) {
                ViewManager wm = a.getWindowManager();
                View decor = r.window.getDecorView();
                wm.updateViewLayout(decor, l);
            }
        }
        r.activity.mVisibleFromServer = true;
        mNumVisibleActivities++;
        if (r.activity.mVisibleFromClient) {
        //设置可见 获取WindowManager 增加view 和WMS通讯 
            r.activity.makeVisible();
        }
    }
    r.nextIdle = mNewActivities;
    mNewActivities = r;
    //和AMS通讯 感兴趣的能够自己跟一下
    Looper.myQueue().addIdleHandler(new Idler());
}
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {
        //获取到ActivityClientRecord
    final ActivityClientRecord r = mActivities.get(token);
    if (r == null || r.activity.mFinished) {
        return null;
    }
    if (finalStateRequest) {
        r.hideForNow = false;
        r.activity.mStartedActivity = false;
    }
    try {
        r.activity.onStateNotSaved();
        r.activity.mFragments.noteStateNotSaved();
        checkAndBlockForNetworkAccess();
        if (r.pendingIntents != null) {
            deliverNewIntents(r, r.pendingIntents);
            r.pendingIntents = null;
        }
        if (r.pendingResults != null) {
            deliverResults(r, r.pendingResults, reason);
            r.pendingResults = null;
        }
        //看是否履行OnRestart 以及履行OnResume
        r.activity.performResume(r.startsNotResumed, reason);
        r.state = null;
        r.persistentState = null;
        设置状况为ON_RESUME
        r.setState(ON_RESUME);
        reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
    } catch (Exception e) {
    }
    return r;
}
//调用Activity的performResume
final void performResume(boolean followedByPause, String reason) {
//分发resume
    dispatchActivityPreResumed();
    //假如stop了需求履行onRestart
    performRestart(true /* start */, reason);
    mFragments.execPendingActions();
    mLastNonConfigurationInstances = null;
    if (mAutoFillResetNeeded) {
        mAutoFillIgnoreFirstResumePause = followedByPause;
        if (mAutoFillIgnoreFirstResumePause && DEBUG_LIFECYCLE) {
        }
    }
    mCalled = false;
    //调用activity的onResume
    mInstrumentation.callActivityOnResume(this);
    mCalled = false;
    //给Fragments分发Resume
    mFragments.dispatchResume();
    mFragments.execPendingActions();
    //履行onPostResume
    onPostResume();
    //分发postresume监听
    dispatchActivityPostResumed();
}
//Instrumentation调用resume
public void callActivityOnResume(Activity activity) {
    activity.mResumed = true;
    activity.onResume();
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                am.match(activity, activity, activity.getIntent());
            }
        }
    }
}
//Activity的resume
protected void onResume() {
    //分发Resume的监听
    dispatchActivityResumed();
    mActivityTransitionState.onResume(this);
    enableAutofillCompatibilityIfNeeded();
    if (mAutoFillResetNeeded) {
        if (!mAutoFillIgnoreFirstResumePause) {
            View focus = getCurrentFocus();
            if (focus != null && focus.canNotifyAutofillEnterExitEvent()) {
                getAutofillManager().notifyViewEntered(focus);
            }
        }
    }
    notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_RESUME);
    mCalled = true;
}

ResumeActivityItemexecute履行到ActivityThreadhandleResumeActivity,判别是否是stoped来履行onRestart 接着履行OnResume,而且设置状况为ON_RESUME,调用ActivitymakeVisible就和WMS通讯了,这个咱们后边再讲。在客户端处理完成之后经过IDLEHandler和AMS通讯,AMS再更新Activity相关的信息,感兴趣的能够自己去看看了。

总结

至此,整个Activity的创立流程就结束了,从Launcher的点击一直到ActivityOnResume的履行。咱们来简略的文字总结下流程: 1.在LauncherItemClickHandler,终究会调用到ActivitystartActivity函数,它会调用到InstrumentationexecStartActivity函数。

2.经过InstrumentationexecStartActivity进行了两次IPC通讯,获取到ATMS调用startActivity,它会根据intent来查找activity信息,而且暂停当时Activity,调用到ActivityStackSupervisorstartSpecificActivityLocked判别进程是否存在(wpc.thread),假如进程存在调用realStartActivityLocked来敞开Activity,否则调用startProcess敞开进程。

3.咱们第一次进来进程是不存在的,所以咱们会进入敞开进程的流程,调用 ProcessListstartProcessLocked设置entryPointActivityThread,经过ZygoteProcess来设置参数,ZygoteConnect发送数据给Zygote,当ZygoteServer接收到数据之后敞开ActivityThreadmain会创立ActivityThread 调用attach(留意此刻咱们现已在子进程了),然后IPC告知AMS 开始attachApplication服务端会把进程存入mPidsSelfLocked进行办理,然后经过thread.bindApplication(IPC)告知运用端,运用进程就能够创立Application loadedApk Context调用ApplicationOnCreate。 创立完进程就4次IPC通讯了(start的时分两次,创立进程之后告知AMS 持续AMS的流程 一次,thread.bindApplication 一次)。

4.客户端创立完Application之后在ATMS中会调用attachApplication 接着会调用realStartActivityLocked创立ClientTransaction,设置callbackLaunchActivityItem 增加stateRequestResumeActivityItem,调用scheduleTransaction(IPC)调用到ActivityThreadscheduleTransaction函数,调用executeCallBack 也便是履行LaunchActivityItem的execute 它会调用到ActivityThread的handleLaunchActivity,会创立ActivityContext ,经过Instrumentation 反射创立Activity 调用activity的attach 绑定window 再调用callActivityOnCreate 履行ActivityOnCreate。在ActivityOnCreate中分发监听给ActivityLifecycleCallbacks。最后设置当时状况为ON_CREATE

5.OnCreate之后就会履行executeLifecycleState,之前传递的是ResumeActivityItem,接着调用cycleToPath,之前设置了是ON_CREATE,所以现在里边会存储2 也便是需求履行OnStart,调用performLifecycleSequence 调用ActivityThread.handleStartActivity 分发ActivityLifecycleCallbacks,分发Fragments 调用InstrumentationcallActivityOnStart 设置state为ON_START

6.调用ResumeActivityItemexecute,调用到ActivityThread.handleResumeActivity,调用performResume 分发resume事情给ActivityLifecycleCallbacks,分发Fragments,履行onPostResume 分发onPostResume监听 调用InstrumentationcallActivityOnresume 会调用到ActivityonResume。 最后会再调用r.activity.makeVisible经过WindowManager 增加当时viewWMS(IPC)通讯,再给Looper发送一个IdlerAMS(IPC)通讯,让AMS设置Activity的状况信息。

【Android Framework】ActivityManagerService(二) (含视频)

面试

Q1:介绍一下Activity的发动流程。

A1:分两种状况,进程未存在,进程已存在。 没存在的话会先跟Zygote树立通讯,由Zygote Fork出来子进程 并进入ActivityThread,然后告知AMS``attachApplicationAMS再告知客户端 创立ApplicationloadedApkInstrumentation 经过InstrumentationcallApplicationOncreate履行ApplicationOncreate 生命周期。 接着AMS会调用realStartActivity 创立ClientTransaction,设置callbackLaunchActivityItem 增加stateRequestResumeActivityItem,分别履行OnCreate,onStart,OnResume,在OnResume中会调用WM和WMS通讯制作UI,再给Looper发送一个IdlerAMS(IPC)通讯,让AMS设置Activity的状况信息。

Q2:ActivityManagerService在创立运用的时分为什么运用socket 而不是用Binder呢?

A2:这个交给大家自己去想哈~

好了,关于AMS是怎样敞开运用,怎样敞开Activity的流程咱们都讲完了,Activity是最复杂的一个组件了,许多逻辑,一次彻底理解是不可能的,当咱们需求剖析的时分再回来看吧。下一次咱们讲另外一个组件Service。大家 下次再会吧。

在线视频: www.bilibili.com/video/BV17m…